Java Code Examples for com.google.common.base.Optional#of()

The following examples show how to use com.google.common.base.Optional#of() .
Example 1
Project: tac-kbp-eal   File: SummarizeDocScores2016.java    License: MIT License 6 votes vote down vote up
private void writeSummaryArgScores(
    final Collection<String> focusTeamSubmissionNames,
    final ImmutableMap<String, SystemScores> systemNameToScores,
    final ImmutableSetMultimap<String, String> teamsToSystems, final Writer out)
    throws IOException {
  out.write("Document Level Argument Summary Score:\n\n");

  final Map<String, SystemScores> teamScores =
      Maps.filterKeys(systemNameToScores, in(focusTeamSubmissionNames));

  final ImmutableMap.Builder<String, SystemScores> argScoresToPrint = ImmutableMap.builder();
  argScoresToPrint.putAll(teamScores);
  final Optional<Map<Integer, PercentileComputer.Percentiles>> medianScores;
  if (teamsToSystems.keySet().size() > 3) {
    medianScores = Optional.of(Maps.transformValues(
        findMedianSystemsBy(systemNameToScores, teamsToSystems, EXTRACT_ARG_BOOTSTRAP_MEDIAN),
        EXTRACT_ARG_BOOTSTRAP_SCORES));
  } else {
    medianScores = Optional.absent();
  }

  argScoresToPrint.put("Max", BY_BOOTSTRAP_MEDIAN_ARG_SCORE.max(systemNameToScores.values()));
  printBootstrapScoresChart(argScoresToPrint.build(), EXTRACT_ARG_BOOTSTRAP_SCORES, medianScores, out);

  out.write("The argument score is described in section 7.1 of the task guidelines.\n\n");
}
 
Example 2
Project: Baragon   File: AgentCheckinResource.java    License: Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{clusterName}/shutdown")
public AgentCheckInResponse removeAgent(@PathParam("clusterName") String clusterName,
                                        @QueryParam("status") boolean status,
                                        BaragonAgentMetadata agent) {
  LOG.info(String.format("Notified of shutdown for agent %s", agent.getAgentId()));
  AgentCheckInResponse response;
  try {
    if (elbManager.isElbConfigured()) {
      response = elbManager.attemptRemoveAgent(agent, loadBalancerDatastore.getLoadBalancerGroup(clusterName), clusterName, status);
    } else if (googleCloudManager.isConfigured()) {
      response = googleCloudManager.checkHealthOfAgentOnShutdown(agent);
    } else {
      response = new AgentCheckInResponse(TrafficSourceState.DONE, Optional.absent(), 0L);
    }
  } catch (Exception e) {
    LOG.error("Could not register agent shutdown", e);
    response = new AgentCheckInResponse(TrafficSourceState.ERROR, Optional.of(e.getMessage()), 0L);
  }
  return response;
}
 
Example 3
Project: incubator-gobblin   File: MeteredOutputStream.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Find the lowest {@link MeteredOutputStream} in a chain of {@link FilterOutputStream}s.
 */
public static Optional<MeteredOutputStream> findWrappedMeteredOutputStream(OutputStream os) {
  if (os instanceof FilterOutputStream) {
    try {
      Optional<MeteredOutputStream> meteredOutputStream =
          findWrappedMeteredOutputStream(FilterStreamUnpacker.unpackFilterOutputStream((FilterOutputStream) os));
      if (meteredOutputStream.isPresent()) {
        return meteredOutputStream;
      }
    } catch (IllegalAccessException iae) {
      log.warn("Cannot unpack input stream due to SecurityManager.", iae);
      // Do nothing, we can't unpack the FilterInputStream due to security restrictions
    }
  }
  if (os instanceof MeteredOutputStream) {
    return Optional.of((MeteredOutputStream) os);
  }
  return Optional.absent();
}
 
Example 4
Project: Baragon   File: ClassicLoadBalancer.java    License: Apache License 2.0 6 votes vote down vote up
private boolean shouldRegister(BaragonAgentMetadata agent, String elbName, List<LoadBalancerDescription> elbs) {
  Optional<LoadBalancerDescription> matchingElb = Optional.absent();
  for (LoadBalancerDescription elb : elbs) {
    if (elbName.equals(elb.getLoadBalancerName())) {
      matchingElb = Optional.of(elb);
    }
  }
  if (!matchingElb.isPresent()) {
    return false;
  }

  boolean alreadyRegistered = false;
  for (Instance instance : matchingElb.get().getInstances()) {
    if (agent.getEc2().getInstanceId().get().equals(instance.getInstanceId())) {
      alreadyRegistered = true;
    }
  }

  return !alreadyRegistered && (isVpcOk(agent, matchingElb.get()) || !configuration.get().isCheckForCorrectVpc());
}
 
Example 5
Project: incubator-gobblin   File: KafkaKeyValueProducerPusherTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws IOException {
  // Test that the scoped config overrides the generic config
  Pusher pusher = new KafkaKeyValueProducerPusher<byte[], byte[]>("127.0.0.1:dummy", TOPIC,
      Optional.of(ConfigFactory.parseMap(ImmutableMap.of(
          ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:" + this.kafkaTestHelper.getKafkaServerPort()))));

  String msg1 = "msg1";
  String msg2 = "msg2";

  pusher.pushMessages(Lists.newArrayList(Pair.of("key1", msg1.getBytes()), Pair.of("key2", msg2.getBytes())));

  try {
    Thread.sleep(1000);
  } catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
  }

  ConsumerIterator<byte[], byte[]> iterator = this.kafkaTestHelper.getIteratorForTopic(TOPIC);

  assert(iterator.hasNext());

  MessageAndMetadata<byte[], byte[]> messageAndMetadata = iterator.next();

  Assert.assertEquals(new String(messageAndMetadata.key()), "key1");
  Assert.assertEquals(new String(messageAndMetadata.message()), msg1);
  assert(iterator.hasNext());

  messageAndMetadata = iterator.next();
  Assert.assertEquals(new String(messageAndMetadata.key()), "key2");
  Assert.assertEquals(new String(messageAndMetadata.message()), msg2);

  pusher.close();
}
 
Example 6
Project: opensharding-spi-impl   File: UpdateSQLRevertExecutor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<String> revertSQL() {
    if (sqlRevertContext.getUndoData().isEmpty()) {
        return Optional.absent();
    }
    sqlBuilder.appendLiterals(DefaultKeyword.UPDATE);
    sqlBuilder.appendLiterals(sqlRevertContext.getActualTable());
    sqlBuilder.appendUpdateSetAssignments(sqlRevertContext.getUpdateSetAssignments().keySet());
    sqlBuilder.appendWhereCondition(sqlRevertContext.getPrimaryKeyColumns());
    return Optional.of(sqlBuilder.toSQL());
}
 
Example 7
Project: java-obd-adapter   File: ProbingDiagnosticStatusGatewayFactory.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<? extends DiagnosticStatusGateway> probeSingleTransport(DiagnosticTransport transport) {
	log.info("probing transport {}", transport);

	ProbingDiagnosticStatusGateway diagnosticStatusGateway = new ProbingElmDiagnosticStatusGateway(transport);
	if (diagnosticStatusGateway.probe()) {
		log.info("probe OK");
		return Optional.of(diagnosticStatusGateway);
	} else {
		log.info("probe FAIL");
		diagnosticStatusGateway.close();
		return Optional.absent();
	}
}
 
Example 8
Project: signalfx-java   File: MetricMetadataImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<SignalFxProtocolBuffers.MetricType> getMetricType(Metric metric) {
    Metadata existingMetaData = metaDataCollection.get(metric);
    if (existingMetaData == null || existingMetaData.metricType == null) {
        return Optional.absent();
    } else {
        return Optional.of(existingMetaData.metricType);
    }
}
 
Example 9
Project: ServerListPlus   File: CanaryPlugin.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public Optional<String> load(FaviconSource source) throws Exception {
    // Try loading the favicon
    BufferedImage image = FaviconHelper.loadSafely(core, source);
    if (image == null) return Optional.absent(); // Favicon loading failed
    else return Optional.of(CanaryFavicon.create(image)); // Success!
}
 
Example 10
Project: incubator-gobblin   File: HiveWorkUnit.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the partition keys if this {@link WorkUnit} is for a partitioned table.
 * If not, return {@link Optional#absent()}
 */
public Optional<List<FieldSchema>> getPartitionKeys() {
  String serialzed = this.getProp(HIVE_PARTITION_KEYS);
  if (serialzed == null) {
    return Optional.absent();
  }
  List<FieldSchema> deserialized = GSON.fromJson(serialzed, FIELD_SCHEMA_TYPE);
  return Optional.of(deserialized);
}
 
Example 11
Project: distributedlog   File: ZKLogMetadataStore.java    License: Apache License 2.0 5 votes vote down vote up
public ZKLogMetadataStore(
        DistributedLogConfiguration conf,
        URI namespace,
        ZooKeeperClient zkc,
        OrderedScheduler scheduler) {
    this.namespace = namespace;
    this.nsOptional = Optional.of(this.namespace);
    this.zkc = zkc;
    this.nsWatcher = new ZKNamespaceWatcher(conf, namespace, zkc, scheduler);
}
 
Example 12
Project: incubator-gobblin   File: HiveRegistrationPolicyBase.java    License: Apache License 2.0 5 votes vote down vote up
public HiveRegistrationPolicyBase(State props) throws IOException {
  Preconditions.checkNotNull(props);
  this.props = new HiveRegProps(props);
  if (props.contains(HiveRegistrationPolicyBase.HIVE_FS_URI)) {
    this.fs = FileSystem.get(URI.create(props.getProp(HiveRegistrationPolicyBase.HIVE_FS_URI)), new Configuration());
  } else {
    this.fs = FileSystem.get(new Configuration());
  }
  this.sanitizeNameAllowed = props.getPropAsBoolean(HIVE_SANITIZE_INVALID_NAMES, true);
  this.dbNamePattern = props.contains(HIVE_DATABASE_REGEX)
      ? Optional.of(Pattern.compile(props.getProp(HIVE_DATABASE_REGEX))) : Optional.<Pattern> absent();
  this.tableNamePattern = props.contains(HIVE_TABLE_REGEX)
      ? Optional.of(Pattern.compile(props.getProp(HIVE_TABLE_REGEX))) : Optional.<Pattern> absent();
  this.dbNamePrefix = props.getProp(HIVE_DATABASE_NAME_PREFIX, StringUtils.EMPTY);
  this.dbNameSuffix = props.getProp(HIVE_DATABASE_NAME_SUFFIX, StringUtils.EMPTY);
  this.tableNamePrefix = props.getProp(HIVE_TABLE_NAME_PREFIX, StringUtils.EMPTY);
  this.tableNameSuffix = props.getProp(HIVE_TABLE_NAME_SUFFIX, StringUtils.EMPTY);
  this.emptyInputPathFlag = props.getPropAsBoolean(MAPREDUCE_JOB_INPUT_PATH_EMPTY_KEY, false);
  this.metricContext = Instrumented.getMetricContext(props, HiveRegister.class);

  // Get Topic-specific config object doesn't require any runtime-set properties in prop object, safe to initialize
  // in constructor.
  if (this.props.getProperties().containsKey(KafkaSource.TOPIC_NAME)) {
    Timer.Context context = this.metricContext.timer(CONFIG_FOR_TOPIC_TIMER).time();
    configForTopic =
        ConfigStoreUtils.getConfigForTopic(this.props.getProperties(), KafkaSource.TOPIC_NAME, this.configClient);
    context.close();
  }
}
 
Example 13
Project: envelope   File: StepUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Optional<Step> getStepForName(String name, Set<Step> steps) {
  for (Step step : steps) {
    if (step.getName().equals(name)) {
      return Optional.of(step);
    }
  }
  
  return Optional.absent();
}
 
Example 14
Project: qconfig   File: GetRestConfigFileServlet.java    License: MIT License 5 votes vote down vote up
private Optional<Long> getVersion(HttpServletRequest req) {
    String strVersion = req.getParameter(Constants.VERSION_NAME);
    // 使用isNumeric来判断,字母的,乱写的,写错的version也会走这个分支,然后去请求最新的版本,
    // 但是也不知道是不是有人带上字母来请求,还是保持原来的逻辑
    if (Strings.isNullOrEmpty(strVersion) || !StringUtils.isNumeric(strVersion)) {
        return Optional.absent();
    } else {
        return Optional.of(Numbers.toLong(strVersion));
    }
}
 
Example 15
Project: Baragon   File: BaragonResponse.java    License: Apache License 2.0 4 votes vote down vote up
public static BaragonResponse requestDoesNotExist(String requestId) {
  return new BaragonResponse(requestId, BaragonRequestState.CANCELED, Optional.<String>of(String.format("Request %s does not exist", requestId)), Optional.<Map<String, Collection<AgentResponse>>>absent(), Optional.<BaragonRequest>absent(), false);
}
 
Example 16
Project: emodb   File: AllTablesReportOptions.java    License: Apache License 2.0 4 votes vote down vote up
public void setFromTableUuid(long fromTableUuid) {
    _fromTableUuid = Optional.of(fromTableUuid);
}
 
Example 17
Project: SimpleWeibo   File: BuilderSpec.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns a representation of the given {@code @RetroWeibo.Builder} class or interface. If the
 * class or interface has abstract methods that could not be part of any builder, emits error
 * messages and returns null.
 */
private Optional<Builder> builderFrom(
    TypeElement builderTypeElement, Optional<ExecutableElement> validateMethod) {

  // We require the builder to have the same type parameters as the @RetroWeibo class, meaning the
  // same names and bounds. In principle the type parameters could have different names, but that
  // would be confusing, and our code would reject it anyway because it wouldn't consider that
  // the return type of Foo<U> build() was really the same as the declaration of Foo<T>. This
  // check produces a better error message in that case and similar ones.

  boolean ok = true;
  int nTypeParameters = autoValueClass.getTypeParameters().size();
  if (nTypeParameters != builderTypeElement.getTypeParameters().size()) {
    ok = false;
  } else {
    for (int i = 0; i < nTypeParameters; i++) {
      TypeParameterElement autoValueParam = autoValueClass.getTypeParameters().get(i);
      TypeParameterElement builderParam = builderTypeElement.getTypeParameters().get(i);
      if (!autoValueParam.getSimpleName().equals(builderParam.getSimpleName())) {
        ok = false;
        break;
      }
      Set<TypeMirror> autoValueBounds = new TypeMirrorSet(autoValueParam.getBounds());
      Set<TypeMirror> builderBounds = new TypeMirrorSet(builderParam.getBounds());
      if (!autoValueBounds.equals(builderBounds)) {
        ok = false;
        break;
      }
    }
  }
  if (!ok) {
    errorReporter.reportError(
        "Type parameters of " + builderTypeElement + " must have same names and bounds as "
            + "type parameters of " + autoValueClass, builderTypeElement);
    return Optional.absent();
  }

  String typeParams = TypeSimplifier.actualTypeParametersString(autoValueClass);

  List<ExecutableElement> buildMethods = new ArrayList<ExecutableElement>();
  List<ExecutableElement> setterMethods = new ArrayList<ExecutableElement>();
  // For each abstract method (in builderTypeElement or inherited), check that it is either
  // a setter method or a build method. A setter method has one argument and returns
  // builderTypeElement. A build method has no arguments and returns the @RetroWeibo class.
  // Record each method in one of the two lists.
  for (ExecutableElement method : abstractMethods(builderTypeElement)) {
    boolean thisOk = false;
    int nParameters = method.getParameters().size();
    if (nParameters == 0
        && TYPE_EQUIVALENCE.equivalent(method.getReturnType(), autoValueClass.asType())) {
      buildMethods.add(method);
      thisOk = true;
    } else if (nParameters == 1
        && TYPE_EQUIVALENCE.equivalent(method.getReturnType(), builderTypeElement.asType())) {
      setterMethods.add(method);
      thisOk = true;
    }
    if (!thisOk) {
      errorReporter.reportError(
          "Builder methods must either have no arguments and return "
              + autoValueClass + typeParams + " or have one argument and return "
              + builderTypeElement + typeParams,
          method);
      ok = false;
    }
  }
  if (buildMethods.isEmpty()) {
    errorReporter.reportError(
        "Builder must have a single no-argument method returning "
            + autoValueClass + typeParams,
        builderTypeElement);
    ok = false;
  } else if (buildMethods.size() > 1) {
    // More than one eligible build method. Emit an error for each one, that is attached to
    // that build method.
    for (ExecutableElement buildMethod : buildMethods) {
      errorReporter.reportError(
          "Builder must have a single no-argument method returning "
              + autoValueClass + typeParams,
          buildMethod);
    }
    ok = false;
  }

  if (ok) {
    return Optional.of(new Builder(
        builderTypeElement,
        Iterables.getOnlyElement(buildMethods),
        setterMethods,
        validateMethod));
  } else {
    return Optional.absent();
  }
}
 
Example 18
Project: incubator-gobblin   File: FSSpecStore.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Optional<URI> getSpecStoreURI() {
  return Optional.of(this.fsSpecStoreDirPath.toUri());
}
 
Example 19
Project: OpenPeripheral   File: AnnotationMetaExtractor.java    License: MIT License 4 votes vote down vote up
private static Optional<String> getReturnSignal(AnnotatedElement element, Optional<String> defaultValue) {
	if (element == null) return defaultValue;
	final ReturnSignal ret = element.getAnnotation(ReturnSignal.class);
	return ret != null? Optional.of(ret.value()) : defaultValue;
}
 
Example 20
Project: usergrid   File: MvccEntitySerializationStrategyV1ImplTest.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * We no longer support partial writes, ensure that an exception is thrown when this occurs after v3
 * @throws com.netflix.astyanax.connectionpool.exceptions.ConnectionException
 */
@Test
public void writeLoadDeletePartial() throws ConnectionException {

    final Id applicationId = new SimpleId( "application" );

    ApplicationScope context = new ApplicationScopeImpl( applicationId );


    final UUID entityId = UUIDGenerator.newTimeUUID();
    final UUID version = UUIDGenerator.newTimeUUID();
    final String type = "test";

    final Id id = new SimpleId( entityId, type );

    Entity entity = new Entity( id );

    EntityUtils.setVersion( entity, version );


    BooleanField boolField = new BooleanField( "boolean", false );
    DoubleField doubleField = new DoubleField( "double", 1d );
    IntegerField intField = new IntegerField( "long", 1 );
    LongField longField = new LongField( "int", 1l );
    StringField stringField = new StringField( "name", "test" );
    UUIDField uuidField = new UUIDField( "uuid", UUIDGenerator.newTimeUUID() );

    entity.setField( boolField );
    entity.setField( doubleField );
    entity.setField( intField );
    entity.setField( longField );
    entity.setField( stringField );
    entity.setField( uuidField );


    MvccEntity saved = new MvccEntityImpl( id, version, MvccEntity.Status.PARTIAL, Optional.of( entity ) );


    //persist the entity
    serializationStrategy.write( context, saved ).execute();

}