/** * Looks up an instance by name and type. * <p> * This finds the instance matching the specified name, ensuring it is of the specified type. * Instances may have alternate names (aliases), thus the returned instance * may have a name other than that requested. * * @param <S> the enum subtype * @param subtype the enum subtype to match * @param name the enum name to return * @return the named enum * @throws IllegalArgumentException if the name is not found or has the wrong type */ public <S extends T> S lookup(String name, Class<S> subtype) { T result = lookup(name); if (!subtype.isInstance(result)) { throw new IllegalArgumentException(type.getSimpleName() + " name found but did not match expected type: " + name); } return subtype.cast(result); }
/** * Returns the map of known instances by normalized name. * <p> * This method returns all known instances, keyed by the normalized name. * This is equivalent to the result of {@link #lookupAll()} adjusted such * that each entry is keyed by the result of {@link Named#getName()}. * * @return the map of enum instance by name */ public ImmutableMap<String, T> lookupAllNormalized() { // add values that are keyed under the normalized name // keep values keyed under a non-normalized name Map<String, T> result = new HashMap<>(); Map<String, T> others = new HashMap<>(); for (Entry<String, T> entry : lookupAll().entrySet()) { String normalizedName = entry.getValue().getName(); if (entry.getKey().equals(normalizedName)) { result.put(normalizedName, entry.getValue()); } else { others.put(normalizedName, entry.getValue()); } } // include any values that are only keyed under a non-normalized name others.values().forEach(v -> result.putIfAbsent(v.getName(), v)); return ImmutableMap.copyOf(result); }
/** * Finds an instance by name. * <p> * This finds the instance matching the specified name. * Instances may have alternate names (aliases), thus the returned instance * may have a name other than that requested. * * @param name the enum name to return * @return the named enum */ public Optional<T> find(String name) { for (ExtendedEnum<? extends T> child : children) { @SuppressWarnings("unchecked") Optional<T> found = (Optional<T>) child.find(name); if (found.isPresent()) { return found; } } return Optional.empty(); }
/** * Parses business day convention from the input string. * <p> * Parsing is case insensitive. * It leniently handles a variety of known variants of business day conventions. * * @param str the string to parse * @return the parsed value * @throws IllegalArgumentException if the string cannot be parsed */ public static BusinessDayConvention parseBusinessDayConvention(String str) { return BusinessDayConvention.extendedEnum().findLenient(str) .orElseThrow(() -> new IllegalArgumentException( "Unknown BusinessDayConvention value, must be one of " + BusinessDayConvention.extendedEnum().lookupAllNormalized().keySet() + " but was '" + str + "'")); }
public void test_enum_lenient() { ExtendedEnum<SampleNamed> test = ExtendedEnum.of(SampleNamed.class); assertEquals(test.findLenient("Standard"), Optional.of(SampleNameds.STANDARD)); assertEquals(test.findLenient("A1"), Optional.of(SampleNameds.STANDARD)); assertEquals(test.findLenient("A2"), Optional.of(MoreSampleNameds.MORE)); }
public void test_enum_SampleOther() { ExtendedEnum<SampleOther> test = ExtendedEnum.of(SampleOther.class); assertEquals(test.lookupAll(), ImmutableMap.of()); assertEquals(test.alternateNames(), ImmutableMap.of()); assertEquals(test.externalNameGroups(), ImmutableSet.of()); assertThrowsIllegalArg(() -> test.lookup("Rubbish")); assertThrowsIllegalArg(() -> test.lookup(null)); assertEquals(test.toString(), "ExtendedEnum[SampleOther]"); }
public void test_enum_SampleNamed() { ExtendedEnum<SampleNamed> test = ExtendedEnum.of(SampleNamed.class); assertEquals(test.lookupAll(), ImmutableMap.builder() .put("Standard", SampleNameds.STANDARD) .put("ANOTHER2", SampleNamedInstanceLookup2.ANOTHER2) .build()); assertEquals(test.lookupAllNormalized(), ImmutableMap.builder() .put("Standard", SampleNameds.STANDARD) .put("Another2", SampleNamedInstanceLookup2.ANOTHER2) .build()); assertEquals(test.alternateNames(), ImmutableMap.of("Alternate", "Standard", "ALTERNATE", "Standard")); assertEquals(test.getType(), SampleNamed.class); assertEquals(test.find("Standard"), Optional.of(SampleNameds.STANDARD)); assertEquals(test.find("STANDARD"), Optional.of(SampleNameds.STANDARD)); assertEquals(test.find("Rubbish"), Optional.empty()); assertEquals(test.lookup("Standard"), SampleNameds.STANDARD); assertEquals(test.lookup("Alternate"), SampleNameds.STANDARD); assertEquals(test.lookup("ALTERNATE"), SampleNameds.STANDARD); assertEquals(test.lookup("More"), MoreSampleNameds.MORE); assertEquals(test.lookup("More", MoreSampleNameds.class), MoreSampleNameds.MORE); assertEquals(test.lookup("Other"), OtherSampleNameds.OTHER); assertEquals(test.lookup("Other", OtherSampleNameds.class), OtherSampleNameds.OTHER); assertEquals(test.lookup("Another1"), SampleNamedInstanceLookup1.ANOTHER1); assertEquals(test.lookup("Another2"), SampleNamedInstanceLookup2.ANOTHER2); assertThrowsIllegalArg(() -> test.lookup("Rubbish")); assertThrowsIllegalArg(() -> test.lookup(null));
public void test_enum_invalid() { Logger logger = Logger.getLogger(ExtendedEnum.class.getName()); Level level = logger.getLevel(); try { logger.setLevel(Level.OFF); // these return empty instances to avoid ExceptionInInitializerError assertEquals(ExtendedEnum.of(SampleInvalid1.class).lookupAll().isEmpty(), true); assertEquals(ExtendedEnum.of(SampleInvalid2.class).lookupAll().isEmpty(), true); assertEquals(ExtendedEnum.of(SampleInvalid3.class).lookupAll().isEmpty(), true); assertEquals(ExtendedEnum.of(SampleInvalid4.class).lookupAll().isEmpty(), true); assertEquals(ExtendedEnum.of(SampleInvalid5.class).lookupAll().isEmpty(), true); assertEquals(ExtendedEnum.of(SampleInvalid6.class).lookupAll().isEmpty(), true); assertEquals(ExtendedEnum.of(SampleInvalid7.class).lookupAll().isEmpty(), true); } finally { logger.setLevel(level); } }
@Test(dataProvider = "lenient") public void test_lenientLookup_specialNames(String name, RollConvention convention) { assertEquals(RollConvention.extendedEnum().findLenient(name.toLowerCase(Locale.ENGLISH)), Optional.of(convention)); }
public void test_enum_SampleNamed_externals() { ExtendedEnum<SampleNamed> test = ExtendedEnum.of(SampleNamed.class); assertEquals(test.externalNameGroups(), ImmutableSet.of("Foo", "Bar")); assertThrowsIllegalArg(() -> test.externalNames("Rubbish")); ExternalEnumNames<SampleNamed> fooExternals = test.externalNames("Foo"); assertEquals(fooExternals.lookup("Foo1"), SampleNameds.STANDARD); assertEquals(fooExternals.lookup("Foo1", SampleNamed.class), SampleNameds.STANDARD); assertEquals(fooExternals.lookup("Foo1", SampleNamed.class), SampleNameds.STANDARD); assertEquals(fooExternals.externalNames(), ImmutableMap.of("Foo1", "Standard")); assertThrowsIllegalArg(() -> fooExternals.lookup("Rubbish")); assertThrowsIllegalArg(() -> fooExternals.lookup(null)); assertThrowsIllegalArg(() -> fooExternals.lookup("Other", MoreSampleNameds.class)); assertEquals(fooExternals.toString(), "ExternalEnumNames[SampleNamed:Foo]"); ExternalEnumNames<SampleNamed> barExternals = test.externalNames("Bar"); assertEquals(barExternals.lookup("Foo1"), MoreSampleNameds.MORE); assertEquals(barExternals.lookup("Foo2"), SampleNameds.STANDARD); assertEquals(barExternals.reverseLookup(MoreSampleNameds.MORE), "Foo1"); assertEquals(barExternals.reverseLookup(SampleNameds.STANDARD), "Foo2"); assertThrowsIllegalArg(() -> barExternals.reverseLookup(OtherSampleNameds.OTHER)); assertEquals(barExternals.externalNames(), ImmutableMap.of("Foo1", "More", "Foo2", "Standard")); assertEquals(barExternals.toString(), "ExternalEnumNames[SampleNamed:Bar]"); }
/** * Converts an FpML business day convention string to a {@code BusinessDayConvention}. * * @param fmplBusinessDayConventionName the business day convention name used by FpML * @return the business day convention * @throws IllegalArgumentException if the business day convention is not known */ public BusinessDayConvention convertBusinessDayConvention(String fmplBusinessDayConventionName) { return BusinessDayConvention.extendedEnum().externalNames(ENUM_FPML).lookup(fmplBusinessDayConventionName); }
throw new IllegalArgumentException("Unable to call extendedEnum() method on class: " + cls.getName(), ex); if (!enumType.isAssignableFrom(result.getType())) { throw new IllegalArgumentException( "Method extendedEnum() returned an ExtendedEnum with an incompatible type on class: " + cls.getName());
/** * Obtains an instance of the parser, based on the specified selector and trade info plugin. * <p> * The FpML parser has a number of plugin points that can be controlled: * <ul> * <li>the {@linkplain FpmlPartySelector party selector} * <li>the {@linkplain FpmlTradeInfoParserPlugin trade info parser} * <li>the {@linkplain FpmlParserPlugin trade parsers} * <li>the {@linkplain ReferenceData reference data} * </ul> * This method uses the trade parsers registered in {@link FpmlParserPlugin} configuration * and the {@linkplain ReferenceData#standard() standard} reference data. * * @param ourPartySelector the selector used to find "our" party within the set of parties in the FpML document * @param tradeInfoParser the trade info parser * @return the document parser */ public static FpmlDocumentParser of( FpmlPartySelector ourPartySelector, FpmlTradeInfoParserPlugin tradeInfoParser) { return of(ourPartySelector, tradeInfoParser, FpmlParserPlugin.extendedEnum().lookupAllNormalized()); }
/** * Parses roll convention from the input string. * <p> * Parsing is case insensitive. * It leniently handles a variety of known variants of roll conventions. * * @param str the string to parse * @return the parsed value * @throws IllegalArgumentException if the string cannot be parsed */ public static RollConvention parseRollConvention(String str) { return RollConvention.extendedEnum().findLenient(str) .orElseThrow(() -> new IllegalArgumentException( "Unknown RollConvention value, must be one of " + RollConvention.extendedEnum().lookupAllNormalized().keySet() + " but was '" + str + "'")); }
@Test(dataProvider = "name") public void test_lenientLookup_standardNames(DayCount convention, String name) { assertEquals(DayCount.extendedEnum().findLenient(name.toLowerCase(Locale.ENGLISH)).get(), convention); }
/** * Converts an FpML roll convention string to a {@code RollConvention}. * * @param fmplRollConventionName the roll convention name used by FpML * @return the roll convention * @throws IllegalArgumentException if the roll convention is not known */ public RollConvention convertRollConvention(String fmplRollConventionName) { return RollConvention.extendedEnum().externalNames(ENUM_FPML).lookup(fmplRollConventionName); }
/** * Obtains an instance from the set of standard holiday calendars. * <p> * The unique name identifies the calendar in the <i>standard</i> source of calendars. * The standard source is loaded at startup based on the {@code HolidayCalendar.ini} file. * <p> * Applications should generally avoid using this method. * Instead, applications should refer to holidays using {@link HolidayCalendarId}, * resolving them using a {@link ReferenceData}. * <p> * It is possible to combine two or more calendars using the '+' symbol. * For example, 'GBLO+USNY' will combine the separate 'GBLO' and 'USNY' calendars. * * @param uniqueName the unique name of the calendar * @return the holiday calendar */ public static HolidayCalendar of(String uniqueName) { if (uniqueName.contains("+")) { return Splitter.on('+').splitToList(uniqueName).stream() .map(HolidayCalendars::of) .reduce(NO_HOLIDAYS, HolidayCalendar::combinedWith); } return ENUM_LOOKUP.lookup(uniqueName); }
@Override public Set<Tenor> getTenors() { if (!type.isIbor()) { return ImmutableSet.of(); } return IborIndex.extendedEnum().lookupAll().values().stream() .filter(index -> index.getName().startsWith(indexName)) .filter(index -> index.isActive()) .map(index -> index.getTenor()) .sorted() .collect(toImmutableSet()); }
private static IborFixingDepositConvention createByName(String name) { return IborIndex.extendedEnum().find(name) .map(index -> ImmutableIborFixingDepositConvention.of(index)) .orElse(null); }
/** * Parses day count from the input string. * <p> * Parsing is case insensitive. * It leniently handles a variety of known variants of day counts. * * @param str the string to parse * @return the parsed value * @throws IllegalArgumentException if the string cannot be parsed */ public static DayCount parseDayCount(String str) { return DayCount.extendedEnum().findLenient(str) .orElseThrow(() -> new IllegalArgumentException( "Unknown DayCount value, must be one of " + DayCount.extendedEnum().lookupAllNormalized().keySet() + " but was '" + str + "'")); }