Java Code Examples for com.google.common.base.Enums#getIfPresent()

The following examples show how to use com.google.common.base.Enums#getIfPresent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JobLauncherFactory.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * 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..
 * @param metadataTags additional metadata to be added to timing events
 * @return the JobLauncher instance
 * @throws RuntimeException if the instantiation fails
 */
public static JobLauncher newJobLauncher(Properties sysProps, Properties jobProps,
    String launcherTypeValue, SharedResourcesBroker<GobblinScopeTypes> instanceBroker, List<? extends Tag<?>> metadataTags) {
  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, metadataTags);
        case MAPREDUCE:
          return new MRJobLauncher(JobConfigurationUtils.combineSysAndJobProperties(sysProps, jobProps), instanceBroker, metadataTags);
        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);
  }
}
 
Example 2
Source File: QueryUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Try and parse `value` as Enum. Throws `QueryException` if invalid value.
 *
 * @param klass the Enum class.
 * @param value the enum 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 ) );
    }
}
 
Example 3
Source File: HiveSerDeManager.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Get an instance of {@link HiveSerDeManager}.
 *
 * @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 ORC) 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);
  }
}
 
Example 4
Source File: ChartFacadeController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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;
}
 
Example 5
Source File: ReportTableFacadeController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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;
}
 
Example 6
Source File: AbstractCrudController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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;
}
 
Example 7
Source File: DatePartitionedNestedRetriever.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private void initDatePartitionFromGranularity(State state) {
  String granularityProp = state.getProp(PartitionedFileSourceBase.DATE_PARTITIONED_SOURCE_PARTITION_GRANULARITY);
  DatePartitionType partitionType = null;
  if (granularityProp == null) {
    partitionType = PartitionedFileSourceBase.DEFAULT_DATE_PARTITIONED_SOURCE_PARTITION_GRANULARITY;
  } else {
    Optional<DatePartitionType> partitionTypeOpt =
        Enums.getIfPresent(DatePartitionType.class, granularityProp.toUpperCase());
    Preconditions
        .checkState(partitionTypeOpt.isPresent(), "Invalid source partition granularity: " + granularityProp);
    partitionType = partitionTypeOpt.get();
  }
  this.partitionPatternFormatter = DateTimeFormat.forPattern(partitionType.getDateTimePattern());
  this.incrementalUnit = partitionType.getDateTimeFieldType().getDurationType();
}
 
Example 8
Source File: EnumValueConverter.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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 ConfigException 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 ConfigException("Enum label %s.{%s} does not exist",
            enumType.getSimpleName(), String.join("|", candidates));
}
 
Example 9
Source File: MRCompactorAvroKeyDedupJobRunner.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 10
Source File: CompactionAvroJobConfigurator.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Refer to MRCompactorAvroKeyDedupJobRunner#getDedupKeyOption()
 */
private MRCompactorAvroKeyDedupJobRunner.DedupKeyOption getDedupKeyOption() {
  if (!this.state.contains(MRCompactorAvroKeyDedupJobRunner.COMPACTION_JOB_DEDUP_KEY)) {
    return MRCompactorAvroKeyDedupJobRunner.DEFAULT_DEDUP_KEY_OPTION;
  }
  Optional<MRCompactorAvroKeyDedupJobRunner.DedupKeyOption> option =
      Enums.getIfPresent(MRCompactorAvroKeyDedupJobRunner.DedupKeyOption.class,
          this.state.getProp(MRCompactorAvroKeyDedupJobRunner.COMPACTION_JOB_DEDUP_KEY).toUpperCase());
  return option.isPresent() ? option.get() : MRCompactorAvroKeyDedupJobRunner.DEFAULT_DEDUP_KEY_OPTION;
}
 
Example 11
Source File: KafkaWorkUnitPacker.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
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());
    }
    throw new IllegalArgumentException("WorkUnit size estimator type " + sizeEstimatorType + " not found");
  }
  return getWorkUnitSizeEstimator(DEFAULT_SIZE_ESTIMATOR_TYPE);
}
 
Example 12
Source File: KafkaWorkUnitPacker.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public static KafkaWorkUnitPacker getInstance(AbstractSource<?, ?> source, SourceState state,
    Optional<MetricContext> metricContext) {
  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, metricContext);
    }
    throw new IllegalArgumentException("WorkUnit packer type " + packerTypeStr + " not found");
  }
  return getInstance(DEFAULT_PACKER_TYPE, source, state, metricContext);
}
 
Example 13
Source File: TimeBasedWriterPartitioner.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private static DatePartitionType getGranularity(State state, int numBranches, int branchId) {
  String propName = ForkOperatorUtils.getPropertyNameForBranch(WRITER_PARTITION_GRANULARITY, numBranches, branchId);
  String granularityValue = state.getProp(propName, DEFAULT_WRITER_PARTITION_GRANULARITY.toString());
  Optional<DatePartitionType> granularity =
      Enums.getIfPresent(DatePartitionType.class, granularityValue.toUpperCase());
  Preconditions.checkState(granularity.isPresent(),
      granularityValue + " is not a valid writer partition granularity");
  return granularity.get();
}
 
Example 14
Source File: KafkaDeserializerExtractor.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a {@link KafkaSchemaRegistry} using the value of {@link #KAFKA_DESERIALIZER_TYPE}, if not set it
 * defaults to {@link SimpleKafkaSchemaRegistry}.
 */
private static KafkaSchemaRegistry<?, ?> getKafkaSchemaRegistry(Properties props)
    throws ReflectiveOperationException {

  Optional<Deserializers> deserializerType =
      Enums.getIfPresent(Deserializers.class, props.getProperty(KAFKA_DESERIALIZER_TYPE).toUpperCase());

  if (deserializerType.isPresent()) {
    return ConstructorUtils.invokeConstructor(deserializerType.get().getSchemaRegistryClass(), props);
  }
  if (props.containsKey(KafkaSchemaRegistry.KAFKA_SCHEMA_REGISTRY_CLASS)) {
    return KafkaSchemaRegistry.get(props);
  }
  return new SimpleKafkaSchemaRegistry(props);
}
 
Example 15
Source File: HiveSerDeWrapper.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * 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<BuiltInHiveSerDe> hiveSerDe = Enums.getIfPresent(BuiltInHiveSerDe.class, serDeType.toUpperCase());
  if (hiveSerDe.isPresent()) {
    return new HiveSerDeWrapper(hiveSerDe.get());
  }
  Preconditions.checkArgument(inputFormatClassName.isPresent(),
      "Missing input format class name for SerDe " + serDeType);
  Preconditions.checkArgument(outputFormatClassName.isPresent(),
      "Missing output format class name for SerDe " + serDeType);
  return new HiveSerDeWrapper(serDeType, inputFormatClassName.get(), outputFormatClassName.get());
}
 
Example 16
Source File: Replica.java    From circus-train with Apache License 2.0 4 votes vote down vote up
private void determineValidityOfReplica(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),
        REPLICATION_EVENT);
  }
  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()
          + ", "
          + FULL_OVERWRITE.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()
        + ", "
        + FULL_OVERWRITE.name()
        + ", or "
        + METADATA_UPDATE.name()
        + ".");
  }
  LOG.debug("Replication modes are compatible.");
}
 
Example 17
Source File: KafkaDeserializerExtractor.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
private static Optional<Deserializers> getDeserializerType(Properties props) {
  Preconditions.checkArgument(props.containsKey(KAFKA_DESERIALIZER_TYPE),
      "Missing required property " + KAFKA_DESERIALIZER_TYPE);
  return Enums.getIfPresent(Deserializers.class, props.getProperty(KAFKA_DESERIALIZER_TYPE).toUpperCase());
}
 
Example 18
Source File: HttpCommandEffector.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private String isValidHttpVerb(String httpVerb) {
    Optional<HttpVerb> state = Enums.getIfPresent(HttpVerb.class, httpVerb.toUpperCase());
    checkArgument(state.isPresent(), "Expected one of %s but was %s", Joiner.on(',').join(HttpVerb.values()), httpVerb);
    return httpVerb;
}
 
Example 19
Source File: DownloadRequestServiceImpl.java    From occurrence with Apache License 2.0 4 votes vote down vote up
/**
 * Processes a callback from Oozie which update the download status.
 */
@Override
public void processCallback(String jobId, String status) {
  Preconditions.checkArgument(!Strings.isNullOrEmpty(jobId), "<jobId> may not be null or empty");
  Preconditions.checkArgument(!Strings.isNullOrEmpty(status), "<status> may not be null or empty");
  Optional<Job.Status> opStatus = Enums.getIfPresent(Job.Status.class, status.toUpperCase());
  Preconditions.checkArgument(opStatus.isPresent(), "<status> the requested status is not valid");
  String downloadId = DownloadUtils.workflowToDownloadId(jobId);

  LOG.debug("Processing callback for jobId [{}] with status [{}]", jobId, status);

  Download download = occurrenceDownloadService.get(downloadId);
  if (download == null) {
    // Download can be null if the oozie reports status before the download is persisted
    LOG.info("Download {} not found [Oozie may be issuing callback before download persisted]", downloadId);
    return;
  }

  Download.Status newStatus = STATUSES_MAP.get(opStatus.get());
  switch (newStatus) {
    case KILLED:
      // Keep a manually cancelled download status as opposed to a killed one
      if (download.getStatus() == Download.Status.CANCELLED) {
        CANCELLED_DOWNLOADS.inc();
        return;
      }

    case FAILED:
      LOG.error(NOTIFY_ADMIN, "Got callback for failed query. JobId [{}], Status [{}]", jobId, status);
      updateDownloadStatus(download, newStatus);
      downloadEmailUtils.sendErrorNotificationMail(download);
      FAILED_DOWNLOADS.inc();
      break;

    case SUCCEEDED:
      SUCCESSFUL_DOWNLOADS.inc();
      updateDownloadStatus(download, newStatus);
      // notify about download
      if (download.getRequest().getSendNotification()) {
        downloadEmailUtils.sendSuccessNotificationMail(download);
      }
      break;

    default:
      updateDownloadStatus(download, newStatus);
      break;
  }
}
 
Example 20
Source File: EnumsExample.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void enums_getIfPresent () {
	
	Optional<Day> friday = Enums.getIfPresent(Day.class, "FRIDAY");
	
    assertEquals(friday.get(), Day.FRIDAY);
}