/** * Create a new {@link JobLauncher}. * * <p> * This method will never return a {@code null}. * </p> * * @param sysProps system configuration properties * @param jobProps job configuration properties * @return newly created {@link JobLauncher} */ public static @Nonnull JobLauncher newJobLauncher(Properties sysProps, Properties jobProps) throws Exception { String launcherTypeValue = sysProps.getProperty(ConfigurationKeys.JOB_LAUNCHER_TYPE_KEY, JobLauncherType.LOCAL.name()); Optional<JobLauncherType> launcherType = Enums.getIfPresent(JobLauncherType.class, launcherTypeValue); if (launcherType.isPresent()) { switch (launcherType.get()) { case LOCAL: return new LocalJobLauncher(JobConfigurationUtils.combineSysAndJobProperties(sysProps, jobProps)); case MAPREDUCE: return new MRJobLauncher(JobConfigurationUtils.combineSysAndJobProperties(sysProps, jobProps)); default: throw new RuntimeException("Unsupported job launcher type: " + launcherType.get().name()); } } else { @SuppressWarnings("unchecked") Class<? extends AbstractJobLauncher> launcherClass = (Class<? extends AbstractJobLauncher>) Class.forName(launcherTypeValue); return launcherClass.getDeclaredConstructor(Properties.class) .newInstance(JobConfigurationUtils.combineSysAndJobProperties(sysProps, jobProps)); } }
/** * Use reflection to validate the Java model. */ @Test public void propertyHasModel() throws ReflectiveOperationException { assume().that(bdioEnum instanceof Bdio.ObjectProperty || bdioEnum instanceof Bdio.DataProperty).isTrue(); Bdio.AllowedOn allowedOn = Enums.getField(bdioEnum).getAnnotation(Bdio.AllowedOn.class); // Check the BdioMetadata class for metadata properties if (allowedOn.metadata()) { assertThat(Stream.of(BdioMetadata.class.getMethods()) .anyMatch(this::methodName)) .named("BdioMetadata").isTrue(); } // Check the model type for other domain assignments assertThat(Stream.of(allowedOn.value()) .filter(bdioClass -> modelTypeMethods(bdioClass).noneMatch(this::methodName)) .map(Bdio.Class::name)) .isEmpty(); }
private ConsumerConfiguration getConsumerConfiguration() { ConsumerConfiguration conf = new ConsumerConfiguration(); if (queryParams.containsKey("ackTimeoutMillis")) { conf.setAckTimeout(Integer.parseInt(queryParams.get("ackTimeoutMillis")), TimeUnit.MILLISECONDS); } if (queryParams.containsKey("subscriptionType")) { checkArgument(Enums.getIfPresent(SubscriptionType.class, queryParams.get("subscriptionType")).isPresent(), "Invalid subscriptionType %s", queryParams.get("subscriptionType")); conf.setSubscriptionType(SubscriptionType.valueOf(queryParams.get("subscriptionType"))); } if (queryParams.containsKey("receiverQueueSize")) { conf.setReceiverQueueSize(Math.min(Integer.parseInt(queryParams.get("receiverQueueSize")), 1000)); } if (queryParams.containsKey("consumerName")) { conf.setConsumerName(queryParams.get("consumerName")); } return conf; }
/** * Try and parse `value` as Enum. Throws `QueryException` if invalid value. * * @param klass Enum class * @param value value */ @SuppressWarnings( { "unchecked", "rawtypes" } ) public static <T> T getEnumValue( Class<T> klass, String value ) { Optional<? extends Enum<?>> enumValue = Enums.getIfPresent( (Class<? extends Enum>) klass, value ); if ( enumValue.isPresent() ) { return (T) enumValue.get(); } else { Object[] possibleValues = klass.getEnumConstants(); throw new QueryParserException( "Unable to parse `" + value + "` as `" + klass + "`, available values are: " + Arrays.toString( possibleValues ) ); } }
public void load() { FileConfiguration config = plugin.getConfig(); loadMessages(config); loadNotificationSound(config.getConfigurationSection("notification-sound")); progressEnabled = config.getBoolean("progress"); for (String disableSkill : config.getStringList("progress-disabled")) { Optional<SkillType> skillType = Enums.getIfPresent(SkillType.class, disableSkill.toUpperCase()); if (skillType.isPresent()) { disabledSkillProgress.add(skillType.get()); } else { plugin.getLogger() .log(Level.WARNING, "The skill type {0} for disabled progress is unknown", disableSkill); } } }
private Change.Status parseStatus(ChangeNotesCommit commit) throws ConfigInvalidException { List<String> statusLines = commit.getFooterLineValues(FOOTER_STATUS); if (statusLines.isEmpty()) { return null; } else if (statusLines.size() > 1) { throw expectedOneFooter(FOOTER_STATUS, statusLines); } Change.Status status = Enums.getIfPresent(Change.Status.class, statusLines.get(0).toUpperCase()).orNull(); if (status == null) { throw invalidFooter(FOOTER_STATUS, statusLines.get(0)); } // All approvals after MERGED and before the next status change get the postSubmit // bit. (Currently the state can't change from MERGED to something else, but just in case.) The // exception is the legacy SUBM approval, which is never considered post-submit, but might end // up sorted after the submit during rebuilding. if (status == Change.Status.MERGED) { for (PatchSetApproval psa : bufferedApprovals) { if (!psa.isLegacySubmit()) { psa.setPostSubmit(true); } } } bufferedApprovals.clear(); return status; }
private PatchSetState parsePatchSetState(ChangeNotesCommit commit) throws ConfigInvalidException { String psIdLine = parseExactlyOneFooter(commit, FOOTER_PATCH_SET); int s = psIdLine.indexOf(' '); if (s < 0) { return null; } String withParens = psIdLine.substring(s + 1); if (withParens.startsWith("(") && withParens.endsWith(")")) { PatchSetState state = Enums.getIfPresent( PatchSetState.class, withParens.substring(1, withParens.length() - 1).toUpperCase()) .orNull(); if (state != null) { return state; } } throw invalidFooter(FOOTER_PATCH_SET, psIdLine); }
@Override public <K, V> CompleteConfiguration<K, V> createConfiguration( Class<K> keyType, Class<V> valueType, Map<String, String> properties ) { MutableConfiguration<K, V> configuration = new MutableConfiguration<K, V>(); configuration.setTypes( keyType, valueType ); if ( properties.containsKey( CONFIG_TTL ) ) { Long ttl = Longs.tryParse( Strings.nullToEmpty( properties.get( CONFIG_TTL ) ) ); Preconditions.checkArgument( ttl != null, "Template config error", CONFIG_TTL ); Optional<ExpiryFunction> expiryFunction; if ( properties.containsKey( CONFIG_TTL_RESET ) ) { expiryFunction = Enums.getIfPresent( ExpiryFunction.class, properties.get( CONFIG_TTL_RESET ) ); } else { expiryFunction = Optional.of( CONFIG_TTL_RESET_DEFAULT ); } Preconditions.checkArgument( expiryFunction.isPresent(), "Template config error", CONFIG_TTL_RESET ); configuration.setExpiryPolicyFactory( expiryFunction.get().createFactory( ttl ) ); } if ( properties.containsKey( CONFIG_STORE_BY_VALUE ) ) { configuration.setStoreByValue( Boolean.valueOf( properties.get( CONFIG_STORE_BY_VALUE ) ) ); } return configuration; }
/** * Get an instance of {@link HiveSerDeManager}. * * @param type The {@link HiveSerDeManager} type. It should be either AVRO, or the name of a class that implements * {@link HiveSerDeManager}. The specified {@link HiveSerDeManager} type must have a constructor that takes a * {@link State} object. * @param props A {@link State} object. To get a specific implementation of {@link HiveSerDeManager}, specify either * one of the values in {@link Implementation} (e.g., AVRO) or the name of a class that implements * {@link HiveSerDeManager} in property {@link #HIVE_ROW_FORMAT}. The {@link State} object is also used to * instantiate the {@link HiveSerDeManager}. */ public static HiveSerDeManager get(State props) { String type = props.getProp(HIVE_ROW_FORMAT, Implementation.AVRO.name()); Optional<Implementation> implementation = Enums.getIfPresent(Implementation.class, type.toUpperCase()); try { if (implementation.isPresent()) { return (HiveSerDeManager) ConstructorUtils.invokeConstructor(Class.forName(implementation.get().toString()), props); } return (HiveSerDeManager) ConstructorUtils.invokeConstructor(Class.forName(type), props); } catch (ReflectiveOperationException e) { throw new RuntimeException( "Unable to instantiate " + HiveSerDeManager.class.getSimpleName() + " with type " + type, e); } }
/** * Creates a new instance for a JobLauncher with a given type * @param sysProps the system/environment properties * @param jobProps the job properties * @param launcherTypeValue the type of the launcher; either a {@link JobLauncherType} value or * the name of the class that extends {@link AbstractJobLauncher} and has a constructor * that has a single Properties parameter.. * @return the JobLauncher instance * @throws RuntimeException if the instantiation fails */ public static JobLauncher newJobLauncher(Properties sysProps, Properties jobProps, String launcherTypeValue, SharedResourcesBroker<GobblinScopeTypes> instanceBroker) { Optional<JobLauncherType> launcherType = Enums.getIfPresent(JobLauncherType.class, launcherTypeValue); try { if (launcherType.isPresent()) { switch (launcherType.get()) { case LOCAL: return new LocalJobLauncher(JobConfigurationUtils.combineSysAndJobProperties(sysProps, jobProps), instanceBroker); case MAPREDUCE: return new MRJobLauncher(JobConfigurationUtils.combineSysAndJobProperties(sysProps, jobProps), instanceBroker); default: throw new RuntimeException("Unsupported job launcher type: " + launcherType.get().name()); } } @SuppressWarnings("unchecked") Class<? extends AbstractJobLauncher> launcherClass = (Class<? extends AbstractJobLauncher>) Class.forName(launcherTypeValue); return launcherClass.getDeclaredConstructor(Properties.class) .newInstance(JobConfigurationUtils.combineSysAndJobProperties(sysProps, jobProps)); } catch (Exception e) { throw new RuntimeException("Failed to create job launcher: " + e, e); } }
@Test public void transform_string_to_enum () { List<String> days = Lists.newArrayList( "WEDNESDAY", "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY"); Function<String, Day> valueOfFunction = Enums.valueOfFunction(Day.class); Iterable<Day> daysAsEnums = Iterables.transform(days, valueOfFunction); assertThat(daysAsEnums, IsIterableWithSize.<Day>iterableWithSize(5)); assertThat(daysAsEnums, IsIterableContainingInOrder. <Day>contains( Day.WEDNESDAY, Day.SUNDAY, Day.MONDAY, Day.TUESDAY, Day.WEDNESDAY)); }
@Test public void transform_string_to_enum_string_converter () { List<String> days = Lists.newArrayList( "WEDNESDAY", "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY"); Function<String, Day> valueOfFunction = Enums.stringConverter(Day.class); Iterable<Day> daysAsEnums = Iterables.transform(days, valueOfFunction); assertThat(daysAsEnums, IsIterableWithSize.<Day>iterableWithSize(5)); assertThat(daysAsEnums, IsIterableContainingInOrder. <Day>contains( Day.WEDNESDAY, Day.SUNDAY, Day.MONDAY, Day.TUESDAY, Day.WEDNESDAY)); }
/** * Gets the isolation level. * * @return The isolation level. */ public int getIsolationLevel() { final Optional<IsolationLevel> e = Enums.getIfPresent(IsolationLevel.class, getProperty(ISOLATION_LEVEL).toUpperCase()); if (!e.isPresent()) { throw new DatabaseEngineRuntimeException(ISOLATION_LEVEL + " must be set and be one of the following: " + EnumSet.allOf(IsolationLevel.class)); } switch (e.get()) { case READ_UNCOMMITTED: return Connection.TRANSACTION_READ_UNCOMMITTED; case READ_COMMITTED: return Connection.TRANSACTION_READ_COMMITTED; case REPEATABLE_READ: return Connection.TRANSACTION_REPEATABLE_READ; case SERIALIZABLE: return Connection.TRANSACTION_SERIALIZABLE; default: // Never happens. throw new DatabaseEngineRuntimeException("New isolation level?!" + e.get()); } }
public Optional<PlayerWorkMode> parse(XmlData data) { Node node = data.getDocument() .getFirstChild() .getAttributes() .getNamedItem("mode"); if (node == null) { return Optional.absent(); } else { return Enums.getIfPresent(PlayerWorkMode.class, node.getNodeValue() .toUpperCase()); } }
/** * Perform basic checks on the first line of the file. * * @throws TermAnnotationParserException In case of problems with the first line in the file. */ private void checkFirstLine() throws TermAnnotationParserException { final String[] arr = nextLine.split("\t"); if (arr.length != 14) { throw new TermAnnotationParserException( "Does not look like HPO disease annotation file. Invalid number of fields in first " + "line, expected 14, was " + arr.length); } if (!Enums.getIfPresent(HpoDiseaseAnnotation.DatabaseSource.class, arr[0]).isPresent()) { throw new TermAnnotationParserException( "Does not look like HPO disease annotation file. First field value was " + arr[0] + " but was expected to be one of " + Arrays.toString(HpoDiseaseAnnotation.DatabaseSource.values())); } }
private static void fillWithDefault ( final List<ColumnLabelProviderInformation> columnInformation ) { columnInformation.add ( new ColumnLabelProviderInformation ( "sourceTimestamp", "sourceTimestamp", true, DEFAULT_INITIAL_SIZE, Collections.<String, String> emptyMap () ) ); for ( final Fields field : Fields.values () ) { if ( Enums.getField ( field ).getAnnotation ( Deprecated.class ) != null ) { // ignore deprecated fields continue; } final Map<String, String> properties = new HashMap<String, String> (); properties.put ( "key", field.getName () ); switch ( field ) { case ACTOR_NAME: properties.put ( "decoration", Decoration.ACTOR.toString () ); break; case EVENT_TYPE: properties.put ( "decoration", Decoration.MONITOR.toString () ); break; default: break; } columnInformation.add ( new ColumnLabelProviderInformation ( field.getName (), "variant", false, DEFAULT_INITIAL_SIZE, properties ) ); } columnInformation.add ( new ColumnLabelProviderInformation ( "entryTimestamp", "entryTimestamp", true, DEFAULT_INITIAL_SIZE, Collections.<String, String> emptyMap () ) ); }
private void determinValidityOfReplica(ReplicationMode replicationMode, Table oldReplicaTable) { // REPLICATION_MODE is a table parameter that was added later it might not be set, so we're checking the // REPLICATION_EVENT to determine if a table was created via CT. String previousEvent = oldReplicaTable.getParameters().get(REPLICATION_EVENT.parameterName()); if (StringUtils.isBlank(previousEvent)) { throw new DestinationNotReplicaException(oldReplicaTable, getHiveConf().getVar(ConfVars.METASTOREURIS)); } LOG.debug("Checking that replication modes are compatible."); Optional<ReplicationMode> replicaReplicationMode = Enums.getIfPresent(ReplicationMode.class, nullToEmpty(oldReplicaTable.getParameters().get(REPLICATION_MODE.parameterName()))); if (replicaReplicationMode.isPresent()) { if (replicaReplicationMode.get() == METADATA_MIRROR && replicationMode != METADATA_MIRROR) { throw new InvalidReplicationModeException("Trying a " + replicationMode.name() + " replication on a table that was previously only " + METADATA_MIRROR.name() + "-ed. This is not possible, rerun with a different table name or change the replication mode to " + METADATA_MIRROR.name() + "."); } if (replicaReplicationMode.get() != METADATA_MIRROR && replicationMode == METADATA_MIRROR) { throw new InvalidReplicationModeException("Trying to " + METADATA_MIRROR.name() + " a previously replicated table. This is not possible, rerun with a different table name or change the replication mode to " + FULL.name() + " or " + METADATA_UPDATE.name() + "."); } } else if (replicationMode == METADATA_MIRROR) { // no replicaReplicationMode found in table settings we assume FULL_REPLICATION was intended. throw new InvalidReplicationModeException("Trying to " + METADATA_MIRROR.name() + " a previously replicated table. This is not possible, rerun with a different table name or change the replication mode to " + FULL.name() + " or " + METADATA_UPDATE.name() + "."); } }
@SuppressWarnings("unchecked") // fieldName and parentClazz are needed for potential reflection to get serde info from a field public static <K> K getValue(String strVal, String fieldName, Class<K> clazz, Class<?> parentClazz) throws RestDslException { try { ServiceQueryReservedValue reservedValue = ServiceQueryReservedValue.fromString(strVal); if (reservedValue != null) { if (reservedValue == ServiceQueryReservedValue.NULL) { return null; } return (K) reservedValue; } if (converters.containsKey(clazz)) { return (K) converters.get(clazz).deserialize(strVal); } if (clazz == String.class) { return (K) strVal; } else if (clazz == Long.class || clazz == long.class) { return (K) Long.valueOf(strVal, 10); } else if (clazz == Integer.class || clazz == int.class) { return (K) Integer.valueOf(strVal, 10); } else if (clazz == ObjectId.class) { return (K) new ObjectId(strVal); } else if (clazz == Boolean.class || clazz == boolean.class) { return (K) Boolean.valueOf(strVal); } else if (clazz.isEnum()) { Class c = clazz; Converter<String, K> converter = Enums.stringConverter(c); return converter.convert(strVal); } else if (clazz == Date.class) { return (K) new Date(Long.valueOf(strVal, 10)); } } catch (Exception e) { throw new RestDslException("Cannot convert '" + strVal + "' to object of class " + clazz.getName(), e, RestDslException.Type.PARAMS_ERROR); } throw new RestDslException("Unsupported type " + clazz.getName() + " for value '" + strVal + "'", RestDslException.Type.PARAMS_ERROR); }
@Override public Stream<Violation> validate(Object input) { ViolationBuilder result = new ViolationBuilder(this, input); // Input is not required to be a map, it can be a list or even a simple string if (input instanceof Map<?, ?> && ((Map<?, ?>) input).containsKey(JsonLdConsts.GRAPH)) { Map<?, ?> bdioEntry = (Map<?, ?>) input; // TODO The bdioEntry map should run through the DataPropertyRange validation // The identifier should always be present if (!bdioEntry.containsKey(JsonLdConsts.ID) || Objects.equals(bdioEntry.get(JsonLdConsts.ID), JsonLdConsts.DEFAULT)) { result.error("DefaultNamedGraphIdentififer"); } for (Bdio.ObjectProperty objectProperty : Bdio.ObjectProperty.values()) { if (bdioEntry.containsKey(objectProperty.toString())) { if (!Enums.getField(objectProperty).getAnnotation(Bdio.AllowedOn.class).metadata()) { result.error("PropertyNotAllowed", objectProperty.name()); } } } for (Bdio.DataProperty dataProperty : Bdio.DataProperty.values()) { if (bdioEntry.containsKey(dataProperty.toString())) { if (!Enums.getField(dataProperty).getAnnotation(Bdio.AllowedOn.class).metadata()) { result.error("PropertyNotAllowed", dataProperty.name()); } } } } return result.build(); }
/** * Object properties must be annotated with {@link Bdio.AllowedOn} and {@link Bdio.ObjectPropertyRange}. */ @Test public void objectPropertyMetadata() { assume().that(bdioEnum).isInstanceOf(Bdio.ObjectProperty.class); assertThat(Enums.getField(bdioEnum).getAnnotation(Bdio.AllowedOn.class)).named("@AllowedOn").isNotNull(); assertThat(Enums.getField(bdioEnum).getAnnotation(Bdio.ObjectPropertyRange.class)).named("@ObjectPropertyRange").isNotNull(); // BDIO object properties are not allowed in named graph metadata assertThat(Enums.getField(bdioEnum).getAnnotation(Bdio.AllowedOn.class).metadata()).named("@AllowedOn.metadata").isFalse(); }
/** * Object properties must be annotated with {@link Bdio.AllowedOn} and {@link Bdio.DataPropertyRange}. */ @Test public void dataPropertyMetadata() { assume().that(bdioEnum).isInstanceOf(Bdio.DataProperty.class); assertThat(Enums.getField(bdioEnum).getAnnotation(Bdio.AllowedOn.class)).named("@AllowedOn").isNotNull(); assertThat(Enums.getField(bdioEnum).getAnnotation(Bdio.DataPropertyRange.class)).named("@DataPropertyRange").isNotNull(); }
@JsonCreator public static SpecEnum forValue(String name) { if (StringUtils.isBlank(name)) { return null; } return Enums.getIfPresent(SpecEnum.class, name.toUpperCase()).orNull(); }
private InclusionStrategy.Include getInclusionStrategy( String inclusionStrategy ) { if ( inclusionStrategy != null ) { Optional<InclusionStrategy.Include> optional = Enums.getIfPresent( InclusionStrategy.Include.class, inclusionStrategy ); if ( optional.isPresent() ) { return optional.get(); } } return InclusionStrategy.Include.NON_NULL; }
private <T extends Enum<T>> T getEnumWithDefault( Class<T> enumKlass, Map<String, List<String>> parameters, String key, T defaultValue ) { if ( parameters == null || parameters.get( key ) == null || parameters.get( key ).isEmpty() ) { return defaultValue; } String value = String.valueOf( parameters.get( key ).get( 0 ) ); return Enums.getIfPresent( enumKlass, value ).or( defaultValue ); }
private DedupKeyOption getDedupKeyOption() { if (!this.dataset.jobProps().contains(COMPACTION_JOB_DEDUP_KEY)) { return DEFAULT_DEDUP_KEY_OPTION; } Optional<DedupKeyOption> option = Enums.getIfPresent(DedupKeyOption.class, this.dataset.jobProps().getProp(COMPACTION_JOB_DEDUP_KEY).toUpperCase()); return option.isPresent() ? option.get() : DEFAULT_DEDUP_KEY_OPTION; }
private KafkaWorkUnitSizeEstimator getWorkUnitSizeEstimator() { if (this.state.contains(KAFKA_WORKUNIT_SIZE_ESTIMATOR_TYPE)) { String sizeEstimatorTypeString = this.state.getProp(KAFKA_WORKUNIT_SIZE_ESTIMATOR_TYPE); Optional<SizeEstimatorType> sizeEstimatorType = Enums.getIfPresent(SizeEstimatorType.class, sizeEstimatorTypeString); if (sizeEstimatorType.isPresent()) { return getWorkUnitSizeEstimator(sizeEstimatorType.get()); } else { throw new IllegalArgumentException("WorkUnit size estimator type " + sizeEstimatorType + " not found"); } } else { return getWorkUnitSizeEstimator(DEFAULT_SIZE_ESTIMATOR_TYPE); } }
public static KafkaWorkUnitPacker getInstance(AbstractSource<?, ?> source, SourceState state) { if (state.contains(KAFKA_WORKUNIT_PACKER_TYPE)) { String packerTypeStr = state.getProp(KAFKA_WORKUNIT_PACKER_TYPE); Optional<PackerType> packerType = Enums.getIfPresent(PackerType.class, packerTypeStr); if (packerType.isPresent()) { return getInstance(packerType.get(), source, state); } else { throw new IllegalArgumentException("WorkUnit packer type " + packerTypeStr + " not found"); } } else { return getInstance(DEFAULT_PACKER_TYPE, source, state); } }
/** * Get an instance of {@link HiveSerDeWrapper}. * * @param serDeType The SerDe type. If serDeType is one of the available {@link HiveSerDeWrapper.BuiltInHiveSerDe}, * the other three parameters are not used. Otherwise, serDeType should be the class name of a {@link SerDe}, * and the other three parameters must be present. */ public static HiveSerDeWrapper get(String serDeType, Optional<String> inputFormatClassName, Optional<String> outputFormatClassName, Optional<String> extension) { Optional<BuiltInHiveSerDe> hiveSerDe = Enums.getIfPresent(BuiltInHiveSerDe.class, serDeType.toUpperCase()); if (hiveSerDe.isPresent()) { return new HiveSerDeWrapper(hiveSerDe.get()); } else { Preconditions.checkArgument(inputFormatClassName.isPresent(), "Missing input format class name for SerDe " + serDeType); Preconditions.checkArgument(outputFormatClassName.isPresent(), "Missing output format class name for SerDe " + serDeType); Preconditions.checkArgument(extension.isPresent(), "Missing file extension for SerDe " + serDeType); return new HiveSerDeWrapper(serDeType, inputFormatClassName.get(), outputFormatClassName.get(), extension.get()); } }
private void loadNotificationSound(ConfigurationSection section) { if (section.getBoolean("enabled")) { volume = (float) section.getDouble("volume"); pitch = (float) section.getDouble("pitch"); String soundType = section.getString("type"); Optional<Sound> sound = Enums.getIfPresent(Sound.class, soundType.toUpperCase()); if (sound.isPresent()) { this.sound = sound.get(); } else { plugin.getLogger().log(Level.WARNING, "Failed to load the sound type"); } } }
public MessageListener(mcMMOAction plugin, Collection<String> messages) { super(params().plugin(plugin).types(CHAT)); shouldRemoveHover = !Enums.getIfPresent(HoverEvent.Action.class, "SHOW_ENTITY").isPresent(); this.plugin = plugin; this.localizedMessages = ImmutableSet.copyOf(messages .stream() .map(message -> numberRemover.matcher(message).replaceAll("")) .collect(Collectors.toSet())); }
private <T extends Enum<T>> T parseEnum(String name, Class<T> enumClass, T def) { if (name == null || name.trim().isEmpty()) { return def; } Optional<T> style = Enums.getIfPresent(enumClass, name.trim().toUpperCase()); if (style.isPresent()) { return style.get(); } return def; }
@Operator public Predicate<ChangeData> submittable(String str) throws QueryParseException { SubmitRecord.Status status = Enums.getIfPresent(SubmitRecord.Status.class, str.toUpperCase()).orNull(); if (status == null) { throw error("invalid value for submittable:" + str); } return new SubmittablePredicate(status); }
/** * Get a Java enum from a Protobuf enum in a safe way. * * @param enumType the class of the enum, e.g: BlaEnum.class * @param name the name of the enum entry, e.g: proto.getWinner().name() * @param <E> the enum Type * @return an enum */ public static <E extends Enum<E>> E enumFromProto(Class<E> enumType, String name) { E result = Enums.getIfPresent(enumType, name).orNull(); if (result == null) { log.error("Invalid value for enum " + enumType.getSimpleName() + ": " + name); } return result; }
/** * Attempt to resolve an enum of the specified type by looking for a label with the * given value, trying all case variations in the process. * * @return the matching enum label (if any) * @throws IllegalArgumentException if no such label matching the given value is found. */ @Override public Enum convert(String value) { Set<String> candidates = Sets.newHashSet(value, value.toUpperCase(), value.toLowerCase()); for (String candidate : candidates) { Optional<? extends Enum> result = Enums.getIfPresent(enumType, candidate); if (result.isPresent()) return result.get(); } throw new IllegalArgumentException(String.format( "No enum constant %s.[%s]", enumType.getName(), collectionToDelimitedString(candidates, "|"))); }