Java Code Examples for java.util.concurrent.TimeUnit#valueOf()

The following examples show how to use java.util.concurrent.TimeUnit#valueOf() . 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: Slf4jReporterStarter.java    From fluo with Apache License 2.0 6 votes vote down vote up
@Override
public List<AutoCloseable> start(Params params) {
  SimpleConfiguration config =
      new FluoConfiguration(params.getConfiguration()).getReporterConfiguration("slf4j");

  if (!config.getBoolean("enable", false)) {
    return Collections.emptyList();
  }

  TimeUnit rateUnit = TimeUnit.valueOf(config.getString("rateUnit", "seconds").toUpperCase());
  TimeUnit durationUnit =
      TimeUnit.valueOf(config.getString("durationUnit", "milliseconds").toUpperCase());
  Logger logger = LoggerFactory.getLogger(config.getString("logger", "metrics"));

  Slf4jReporter reporter = Slf4jReporter.forRegistry(params.getMetricRegistry())
      .convertDurationsTo(durationUnit).convertRatesTo(rateUnit).outputTo(logger).build();
  reporter.start(config.getInt("frequency", 60), TimeUnit.SECONDS);

  log.info("Reporting metrics using slf4j");

  return Collections.singletonList((AutoCloseable) reporter);
}
 
Example 2
Source File: AdInfo.java    From examples with Apache License 2.0 6 votes vote down vote up
public void init(String dimension, int dimensionsDescriptorID)
{
  String[] attributes = dimension.split(":");
  for (String attribute : attributes) {
    String[] keyval = attribute.split("=", 2);
    String key = keyval[0];
    if (key.equals("time")) {
      time = TimeUnit.valueOf(keyval[1]);
      timeBucket = TimeBucket.TIME_UNIT_TO_TIME_BUCKET.get(time);
      timeBucketInt = timeBucket.ordinal();
      time = timeBucket.getTimeUnit();
    } else if (key.equals("publisher")) {
      publisherId = keyval.length == 1 || Boolean.parseBoolean(keyval[1]);
    } else if (key.equals("advertiser")) {
      advertiserId = keyval.length == 1 || Boolean.parseBoolean(keyval[1]);
    } else if (key.equals("location")) {
      adUnit = keyval.length == 1 || Boolean.parseBoolean(keyval[1]);
    } else {
      throw new IllegalArgumentException("Unknown attribute '" + attribute + "' specified as part of dimension!");
    }
  }

  this.dimensionsDescriptorID = dimensionsDescriptorID;
  this.dimension = dimension;
}
 
Example 3
Source File: DataStoreAccesor.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public DataStoreAccesor ( final File basePath, final DataFilePool pool ) throws Exception
{
    this.basePath = basePath;
    this.pool = pool;

    if ( !basePath.isDirectory () )
    {
        throw new IllegalStateException ( String.format ( "'%s' is not a directory", basePath ) );
    }

    final Properties p = new Properties ();
    p.loadFromXML ( new FileInputStream ( new File ( basePath, "settings.xml" ) ) );

    this.time = Long.parseLong ( p.getProperty ( "time" ) );
    this.unit = TimeUnit.valueOf ( p.getProperty ( "unit" ) );
    this.count = Integer.parseInt ( p.getProperty ( "count" ) );
    this.quantizer = new Quantizer ( this.time, this.unit, this.count );
}
 
Example 4
Source File: TimeUnitsParser.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public NormalizedTimeUnit parseNotation(CharSequence notation, int value) {
    String candidate = notation.toString().toUpperCase();
    //jdk5 does not have days, hours or minutes, normalizing to millis
    if (candidate.equals("DAYS")) {
        return millis(value * 24 * 60 * 60 * 1000);
    } else if (candidate.equals("HOURS")) {
        return millis(value * 60 * 60 * 1000);
    } else if (candidate.equals("MINUTES")) {
        return millis(value * 60 * 1000);
    }
    try {
        return new NormalizedTimeUnit(value, TimeUnit.valueOf(candidate));
    } catch (Exception e) {
        throw new InvalidUserDataException("Unable to parse provided TimeUnit: " + notation, e);
    }
}
 
Example 5
Source File: AbstractAggregatingDisplayFilter.java    From kieker with Apache License 2.0 6 votes vote down vote up
public AbstractAggregatingDisplayFilter(final Configuration configuration, final IProjectContext projectContext) {
	super(configuration, projectContext);

	this.numberOfEntries = configuration.getIntProperty(AbstractAggregatingDisplayFilter.CONFIG_PROPERTY_NAME_NUMBER_OF_ENTRIES);
	final String recordTimeunitProperty = projectContext.getProperty(IProjectContext.CONFIG_PROPERTY_NAME_RECORDS_TIME_UNIT);
	TimeUnit recordTimeunit;
	try {
		recordTimeunit = TimeUnit.valueOf(recordTimeunitProperty);
	} catch (final IllegalArgumentException ex) { // already caught in AnalysisController, should never happen
		AbstractAggregatingDisplayFilter.LOGGER.warn("{} is no valid TimeUnit! Using NANOSECONDS instead.", recordTimeunitProperty);
		recordTimeunit = TimeUnit.NANOSECONDS;
	}
	this.timeunit = recordTimeunit;

	this.chartModel = this.createChartModel(this.numberOfEntries);
	this.records = new ConcurrentLinkedQueue<T>();
}
 
Example 6
Source File: DateTruncTransformFunction.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Override
public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) {
  Preconditions.checkArgument(arguments.size() >= 3 && arguments.size() <= 5,
      "Between three to five arguments are required, example: %s", EXAMPLE_INVOCATION);
  String unit = ((LiteralTransformFunction) arguments.get(0)).getLiteral().toLowerCase();
  TransformFunction valueArgument = arguments.get(1);
  Preconditions.checkArgument(
      !(valueArgument instanceof LiteralTransformFunction) && valueArgument.getResultMetadata().isSingleValue(),
      "The second argument of dateTrunc transform function must be a single-valued column or a transform function");
  _mainTransformFunction = valueArgument;
  String inputTimeUnitStr = ((LiteralTransformFunction) arguments.get(2)).getLiteral().toUpperCase();
  _inputTimeUnit = TimeUnit.valueOf(inputTimeUnitStr);

  String timeZone = arguments.size() >= 4 ? ((LiteralTransformFunction) arguments.get(3)).getLiteral() : UTC_TZ;
  String outputTimeUnitStr =
      arguments.size() >= 5 ? ((LiteralTransformFunction) arguments.get(4)).getLiteral().toUpperCase()
          : inputTimeUnitStr;
  TimeZoneKey timeZoneKey = TimeZoneKey.getTimeZoneKey(timeZone);

  _field = getTimestampField(DateTimeZoneIndex.getChronology(timeZoneKey), unit);
  _resultMetadata = LONG_SV_NO_DICTIONARY_METADATA;
  _outputTimeUnit = TimeUnit.valueOf(outputTimeUnitStr);
}
 
Example 7
Source File: SessionReconstructionFilter.java    From kieker with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new session reconstruction filter using the given configuration.
 *
 * @param configuration
 *            The configuration for this component.
 * @param projectContext
 *            The project context for this component. The component will be registered.
 */
public SessionReconstructionFilter(final Configuration configuration, final IProjectContext projectContext) {
	super(configuration, projectContext);

	this.timeunit = super.recordsTimeUnitFromProjectContext;

	final String configTimeunitProperty = configuration.getStringProperty(CONFIG_PROPERTY_NAME_TIMEUNIT);
	TimeUnit configTimeunit;
	try {
		configTimeunit = TimeUnit.valueOf(configTimeunitProperty);
	} catch (final IllegalArgumentException ex) {
		this.logger.warn("{} is no valid TimeUnit! Using inherited value of {} instead.", configTimeunitProperty, this.timeunit.name());
		configTimeunit = this.timeunit;
	}

	this.maxThinkTime = this.timeunit.convert(configuration.getLongProperty(CONFIG_PROPERTY_NAME_MAX_THINK_TIME),
			configTimeunit);

	if (this.maxThinkTime < 0) {
		throw new IllegalArgumentException("value " + CONFIG_PROPERTY_VALUE_MAX_THINK_TIME + " must not be negative (found: " + this.maxThinkTime + ")");
	}

}
 
Example 8
Source File: DagManagerUtils.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * get the job start sla from the dag node config.
 * if time unit is not provided, it assumes time unit is minute.
 * @param dagNode dag node for which flow start sla is to be retrieved
 * @return job start sla in ms
 */
static long getJobStartSla(DagNode<JobExecutionPlan> dagNode) {
  Config jobConfig = dagNode.getValue().getJobSpec().getConfig();
  TimeUnit slaTimeUnit = TimeUnit.valueOf(ConfigUtils.getString(
      jobConfig, ConfigurationKeys.GOBBLIN_JOB_START_SLA_TIME_UNIT, ConfigurationKeys.DEFAULT_GOBBLIN_JOB_START_SLA_TIME_UNIT));

  return slaTimeUnit.toMillis(jobConfig.hasPath(ConfigurationKeys.GOBBLIN_JOB_START_SLA_TIME)
      ? jobConfig.getLong(ConfigurationKeys.GOBBLIN_JOB_START_SLA_TIME)
      : ConfigurationKeys.DEFAULT_GOBBLIN_JOB_START_SLA_TIME);
}
 
Example 9
Source File: PeriodicNotificationTypeAdapter.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public PeriodicNotification deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
        throws JsonParseException {

    JsonObject json = arg0.getAsJsonObject();
    String id = json.get("id").getAsString();
    long period = json.get("period").getAsLong();
    TimeUnit periodTimeUnit = TimeUnit.valueOf(json.get("timeUnit").getAsString());
    long initialDelay = json.get("initialDelay").getAsLong();
    Builder builder = PeriodicNotification.builder().id(id).period(period)
            .initialDelay(initialDelay).timeUnit(periodTimeUnit);

    return builder.build();
}
 
Example 10
Source File: HeadStreamSourceOp.java    From PoseidonX with Apache License 2.0 5 votes vote down vote up
private void initParameters(StreamingConfig conf)
    throws StreamingException
{
    if (conf.containsKey(StreamingConfig.OPERATOR_HEADSTREAM_TIMEUNIT))
    {
        this.timeUnit = TimeUnit.valueOf(conf.getStringValue(StreamingConfig.OPERATOR_HEADSTREAM_TIMEUNIT));
    }
    
    if (conf.containsKey(StreamingConfig.OPERATOR_HEADSTREAM_PERIOD))
    {
        this.period = conf.getIntValue(StreamingConfig.OPERATOR_HEADSTREAM_PERIOD);
    }
    if (conf.containsKey(StreamingConfig.OPERATOR_HEADSTREAM_EVENTNUMPERPERIOD))
    {
        this.eventNumPerPeriod = conf.getIntValue(StreamingConfig.OPERATOR_HEADSTREAM_EVENTNUMPERPERIOD);
    }
    if (conf.containsKey(StreamingConfig.OPERATOR_HEADSTREAM_ISSCHEDULE))
    {
        this.isSchedue = conf.getBooleanValue(StreamingConfig.OPERATOR_HEADSTREAM_ISSCHEDULE);
    }
    if (conf.containsKey(StreamingConfig.OPERATOR_HEADSTREAM_TOTALNUMBER))
    {
        this.totalNum = conf.getIntValue(StreamingConfig.OPERATOR_HEADSTREAM_TOTALNUMBER);
    }
    if (conf.containsKey(StreamingConfig.OPERATOR_HEADSTREAM_DELAYTIME))
    {
        this.delay = conf.getLongValue(StreamingConfig.OPERATOR_HEADSTREAM_DELAYTIME);
    }
}
 
Example 11
Source File: AbstractSshFileSystem.java    From jsch-nio with MIT License 5 votes vote down vote up
public TimeUnit getTimeUnitFromEnvironment( String key ) {
    Object value = environment.get( key );
    if ( value == null ) {
        return null;
    }
    if ( value instanceof TimeUnit ) {
        return (TimeUnit) value;
    }
    return TimeUnit.valueOf( value.toString().toUpperCase() );
}
 
Example 12
Source File: DurationSerialization.java    From heroic with Apache License 2.0 5 votes vote down vote up
private Duration deserializeObject(TreeNode tree, DeserializationContext c)
    throws JsonMappingException {
    if (tree == null) {
        throw c.mappingException("expected object");
    }

    TreeNode node;
    ValueNode valueNode;

    final long duration;
    final TimeUnit unit;

    if ((node = tree.get("duration")) != null && node.isValueNode() &&
        (valueNode = (ValueNode) node).isNumber()) {
        duration = valueNode.asLong();
    } else {
        throw c.mappingException("duration is not a numeric field");
    }

    if ((node = tree.get("unit")) != null && node.isValueNode() &&
        (valueNode = (ValueNode) node).isTextual()) {
        unit = TimeUnit.valueOf(valueNode.asText().toUpperCase());
    } else {
        unit = Duration.DEFAULT_UNIT;
    }

    return new Duration(duration, unit);
}
 
Example 13
Source File: RetentionManager.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private void manageRetentionForTable(String tableNameWithType) {

    // Build retention strategy from table config
    TableConfig tableConfig = _pinotHelixResourceManager.getTableConfig(tableNameWithType);
    if (tableConfig == null) {
      LOGGER.error("Failed to get table config for table: {}", tableNameWithType);
      return;
    }
    SegmentsValidationAndRetentionConfig validationConfig = tableConfig.getValidationConfig();
    String segmentPushType = validationConfig.getSegmentPushType();
    if (!"APPEND".equalsIgnoreCase(segmentPushType)) {
      LOGGER.info("Segment push type is not APPEND for table: {}, skip", tableNameWithType);
      return;
    }
    String retentionTimeUnit = validationConfig.getRetentionTimeUnit();
    String retentionTimeValue = validationConfig.getRetentionTimeValue();
    RetentionStrategy retentionStrategy;
    try {
      retentionStrategy = new TimeRetentionStrategy(TimeUnit.valueOf(retentionTimeUnit.toUpperCase()),
          Long.parseLong(retentionTimeValue));
    } catch (Exception e) {
      LOGGER.warn("Invalid retention time: {} {} for table: {}, skip", retentionTimeUnit, retentionTimeValue);
      return;
    }

    // Scan all segment ZK metadata and purge segments if necessary
    if (TableNameBuilder.isOfflineTableResource(tableNameWithType)) {
      manageRetentionForOfflineTable(tableNameWithType, retentionStrategy);
    } else {
      manageRetentionForRealtimeTable(tableNameWithType, retentionStrategy);
    }
  }
 
Example 14
Source File: StatusController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@GET("/status/get-undeployed-services/avaiability/{availability}/time-unit/{timeUnit}/duration/{duration}")
public List<EnvironmentServiceGroupMap> getUndeployedServicesByAvailability(String availability, String timeUnit, int duration) {
    TimeUnit timeUnitEnum;
    try {
        timeUnitEnum = TimeUnit.valueOf(timeUnit);
    } catch (IllegalArgumentException | NullPointerException e) {
        throw new IllegalArgumentException("Please pass timeUnit parameter in TimeUnit type template", e.getCause());
    }
    return serviceStatusHandler.getUndeployedServicesByAvailability(availability, timeUnitEnum, duration);
}
 
Example 15
Source File: ReporterSetup.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
private static void setupGangliaReporter(BlurConfiguration configuration) {
  long period = configuration.getLong(BLUR_SHARD_METRICS_REPORTER_PREFIX + "ganglia." + "period", 5l);
  TimeUnit unit = TimeUnit.valueOf(configuration.get(BLUR_SHARD_METRICS_REPORTER_PREFIX + "ganglia." + "unit",
      "SECONDS").toUpperCase());
  String host = configuration.get(BLUR_SHARD_METRICS_REPORTER_PREFIX + "ganglia." + "host", "localhost");
  int port = configuration.getInt(BLUR_SHARD_METRICS_REPORTER_PREFIX + "ganglia." + "port", -1);
  String prefix = configuration.get(BLUR_SHARD_METRICS_REPORTER_PREFIX + "ganglia." + "prefix", "");
  boolean compressPackageNames = configuration.getBoolean(BLUR_SHARD_METRICS_REPORTER_PREFIX + "ganglia."
      + "compressPackageNames", false);
  GangliaReporter.enable(Metrics.defaultRegistry(), period, unit, host, port, prefix, MetricPredicate.ALL,
      compressPackageNames);
}
 
Example 16
Source File: TimeUnitTransformerFactory.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public static TimeUnitTransformer getTimeUnitTransformer(@Nonnull TimeUnit inputTimeUnit,
    @Nonnull String outputTimeUnitName) {
  outputTimeUnitName = outputTimeUnitName.toUpperCase();
  try {
    return new JavaTimeUnitTransformer(inputTimeUnit, TimeUnit.valueOf(outputTimeUnitName));
  } catch (Exception e) {
    return new CustomTimeUnitTransformer(inputTimeUnit, outputTimeUnitName);
  }
}
 
Example 17
Source File: AnalysisController.java    From kieker with Apache License 2.0 5 votes vote down vote up
/**
 * This simple helper method validates the configuration object.
 *
 * @param configuration
 *            The configuration object to check and (perhaps) update.
 * @return The configuration object.
 */
private Configuration validateConfiguration(final Configuration configuration) {
	final String stringProperty = configuration.getStringProperty(CONFIG_PROPERTY_NAME_RECORDS_TIME_UNIT);
	try {
		TimeUnit.valueOf(stringProperty);
	} catch (final IllegalArgumentException ignore) {
		LOG.warn("{} is no valid TimeUnit! Using NANOSECONDS instead.", stringProperty);
		configuration.setProperty(CONFIG_PROPERTY_NAME_RECORDS_TIME_UNIT, TimeUnit.NANOSECONDS.name());
	}
	return configuration;
}
 
Example 18
Source File: LabelTimeComposite.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public TimeUnit getTimeUnit() {
  return TimeUnit.valueOf( wTimeUnit.getItem( wTimeUnit.getSelectionIndex() ) );
}
 
Example 19
Source File: AbstractAnalysisComponent.java    From kieker with Apache License 2.0 4 votes vote down vote up
/**
 * Each AnalysisComponent requires a constructor with a Configuration object and a IProjectContext.
 *
 * @param configuration
 *            The configuration for this component.
 * @param projectContext
 *            The project context for this component. The component will be registered.
 *
 * @throws NullPointerException
 *             If configuration or projectContext null
 */
public AbstractAnalysisComponent(final Configuration configuration, final IProjectContext projectContext) throws NullPointerException {
	if (null == projectContext) {
		throw new NullPointerException("Missing projectContext");
	}
	if (null == configuration) {
		throw new NullPointerException("Missing configuration");
	}
	this.projectContext = projectContext;
	// somewhat dirty hack...
	configuration.setDefaultConfiguration(this.getDefaultConfiguration());
	this.configuration = configuration;

	// Get the controller, as we have to register the name
	final AnalysisController ac;
	if (projectContext instanceof AnalysisController) {
		ac = (AnalysisController) projectContext;
	} else {
		throw new InvalidProjectContextException("Invalid analysis controller in constructor");
	}

	// Try to determine the name
	String tmpName = configuration.getStringProperty(CONFIG_NAME);
	while ((tmpName.length() == 0) || !ac.tryRegisterComponentName(tmpName)) {
		tmpName = this.getClass().getSimpleName() + '-' + UNNAMED_COUNTER.incrementAndGet();
	}
	this.name = tmpName;

	// As we have now a name, we can create our logger
	this.logger = LoggerFactory.getLogger(this.getClass().getName() + " (" + this.name + ")");

	// Try the record time unit
	final String recordTimeunitProperty = projectContext.getProperty(IProjectContext.CONFIG_PROPERTY_NAME_RECORDS_TIME_UNIT);
	TimeUnit recordTimeunit;
	try {
		recordTimeunit = TimeUnit.valueOf(recordTimeunitProperty);
	} catch (final IllegalArgumentException ex) { // already caught in AnalysisController, should never happen
		this.logger.warn("{} is no valid TimeUnit! Using NANOSECONDS instead.", recordTimeunitProperty);
		recordTimeunit = TimeUnit.NANOSECONDS;
	}
	this.recordsTimeUnitFromProjectContext = recordTimeunit;
}
 
Example 20
Source File: GroupByPeriodFunction.java    From metron with Apache License 2.0 4 votes vote down vote up
public GroupByPeriodFunction(Properties profilerProperties) {
  periodDurationUnits = TimeUnit.valueOf(PERIOD_DURATION_UNITS.get(profilerProperties, String.class));
  periodDuration = PERIOD_DURATION.get(profilerProperties, Integer.class);
}