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

The following are Jave code examples for showing how to use isPresent() of the com.google.common.base.Optional class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GitHub   File: OkJsons.java   View Source Code Vote up 6 votes
EnumDefinition(TypeElement element, String qualified, String simple) {
  this.qualified = qualified;
  this.simple = simple;

  for (Element e : element.getEnclosedElements()) {
    if (e.getKind() == ElementKind.ENUM_CONSTANT) {
      Optional<OkNamedMirror> nameAnnotation = OkNamedMirror.find(e);
      String name = e.getSimpleName().toString();
      String jsonName = name;

      if (nameAnnotation.isPresent()) {
        String s = nameAnnotation.get().name();
        // just ignore annotation with empty name
        if (!s.isEmpty()) {
          jsonName = s;
        }
      }
      byFirstLetter.put(
          jsonName.charAt(0),
          new EnumConstant(name, jsonName));
    }
  }
}
 
Example 2
Project: url-classifier   File: Authority.java   View Source Code Vote up 6 votes
/** */
private Authority(
    Optional<String> userName, Optional<String> password,
    Optional<Object> host, int portOrNegOne,
    IDNA.Info info) {
  if (host.isPresent()) {
    Object hostObj = host.get();
    Preconditions.checkArgument(
        hostObj instanceof InternetDomainName
        || hostObj instanceof Inet4Address
        || hostObj instanceof Inet6Address,
        "Invalid host", hostObj);
  }

  this.userName = userName;
  this.password = password;
  this.host = host;
  this.portOrNegOne = portOrNegOne;
  this.info = info;
}
 
Example 3
Project: javaide   File: Doc.java   View Source Code Vote up 6 votes
/** Lay out a Break-separated group of Docs in the current Level. */
private static State computeBreakAndSplit(
    CommentsHelper commentsHelper,
    int maxWidth,
    State state,
    Optional<Break> optBreakDoc,
    List<Doc> split) {
  float breakWidth = optBreakDoc.isPresent() ? optBreakDoc.get().getWidth() : 0.0F;
  float splitWidth = getWidth(split);
  boolean shouldBreak =
      (optBreakDoc.isPresent() && optBreakDoc.get().fillMode == FillMode.UNIFIED)
          || state.mustBreak
          || state.column + breakWidth + splitWidth > maxWidth;

  if (optBreakDoc.isPresent()) {
    state = optBreakDoc.get().computeBreaks(state, state.lastIndent, shouldBreak);
  }
  boolean enoughRoom = state.column + splitWidth <= maxWidth;
  state = computeSplit(commentsHelper, maxWidth, split, state.withMustBreak(false));
  if (!enoughRoom) {
    state = state.withMustBreak(true); // Break after, too.
  }
  return state;
}
 
Example 4
Project: tac-kbp-eal   File: AssessmentSpecFormats.java   View Source Code Vote up 6 votes
private static void addAnnotationParts(final AssessedResponse assessedResponse,
    final CorefAnnotation corefAnnotation, final List<String> parts) {
  final ResponseAssessment ann = assessedResponse.assessment();
  parts.add(FieldAssessment.asCharacterOrNil(ann.justificationSupportsEventType()));
  parts.add(FieldAssessment.asCharacterOrNil(ann.justificationSupportsRole()));
  parts.add(FieldAssessment.asCharacterOrNil(ann.entityCorrectFiller()));
  parts.add(FieldAssessment.asCharacterOrNil(ann.baseFillerCorrect()));

  final Optional<Integer> corefId = corefAnnotation.corefId(
      assessedResponse.response().canonicalArgument());
  if (corefId.isPresent()) {
    parts.add(Integer.toString(corefId.get()));
  } else {
    parts.add("NIL");
  }
  parts.add(KBPRealis.asString(ann.realis()));
  parts.add(FillerMentionType.stringOrNil(ann.mentionTypeOfCAS()));
}
 
Example 5
Project: googles-monorepo-demo   File: CharSource.java   View Source Code Vote up 6 votes
/**
 * Returns whether the source has zero chars. The default implementation returns true if
 * {@link #lengthIfKnown} returns zero, falling back to opening a stream and checking for EOF if
 * the length is not known.
 *
 * <p>Note that, in cases where {@code lengthIfKnown} returns zero, it is <i>possible</i> that
 * chars are actually available for reading. This means that a source may return {@code true} from
 * {@code isEmpty()} despite having readable content.
 *
 * @throws IOException if an I/O error occurs
 * @since 15.0
 */
public boolean isEmpty() throws IOException {
  Optional<Long> lengthIfKnown = lengthIfKnown();
  if (lengthIfKnown.isPresent() && lengthIfKnown.get() == 0L) {
    return true;
  }
  Closer closer = Closer.create();
  try {
    Reader reader = closer.register(openStream());
    return reader.read() == -1;
  } catch (Throwable e) {
    throw closer.rethrow(e);
  } finally {
    closer.close();
  }
}
 
Example 6
Project: tac-kbp-eal   File: EventArgScoringAlignment.java   View Source Code Vote up 6 votes
/**
 * Note this will not include system equivalence classes whose representative responses were
 * unassessed.
 */
public ImmutableMap<EquivClassType, AssessedResponse> systemEquivClassToAssessedRepresentativeResponses() {
  final ImmutableMap.Builder<EquivClassType, AssessedResponse> ret = ImmutableMap.builder();

  for (final Map.Entry<EquivClassType, Collection<Response>> systemTRFR : equivalenceClassesToSystemResponses()
      .asMap().entrySet()) {
    final Response representativeResponse = systemOutput()
        .selectFromMultipleSystemResponses(systemTRFR.getValue()).get();
    final Optional<AssessedResponse> optAssessedRepResponse =
        answerKey().assess(representativeResponse);
    if (optAssessedRepResponse.isPresent()) {
      ret.put(systemTRFR.getKey(), optAssessedRepResponse.get());
    }
  }
  return ret.build();
}
 
Example 7
Project: n4js   File: NfarStorageMapper.java   View Source Code Vote up 6 votes
@Override
public Iterable<Pair<IStorage, IProject>> getStorages(URI uri) {
	if (uri.isArchive()) {
		URIBasedStorage storage = new URIBasedStorage(uri);
		String authority = uri.authority();
		URI archiveFileURI = URI.createURI(authority.substring(0, authority.length() - 1));
		Optional<? extends IN4JSEclipseProject> optionalProject = eclipseCore.findProject(archiveFileURI);
		if (optionalProject.isPresent()) {
			return Collections.singletonList(Tuples.<IStorage, IProject> create(storage, optionalProject.get()
					.getProject()));
		} else {
			return Collections.singletonList(Tuples.create(storage, null));
		}
	} else {
		return Collections.emptyList();
	}
}
 
Example 8
Project: tac-kbp-eal   File: FilterAnswerKeyByTypeAndRole.java   View Source Code Vote up 5 votes
private static Optional<LinkingStore> getOptionalLinkingStore(final String linkingParam,
    final Parameters params) throws FileNotFoundException {
  final Optional<File> optLinkingAnnotationStoreDir = params.getOptionalExistingDirectory(
      linkingParam);
  final Optional<LinkingStore> optLinkingAnnotationStore;
  if (optLinkingAnnotationStoreDir.isPresent()) {
    optLinkingAnnotationStore = Optional.of(
        LinkingStoreSource.createFor2015().openLinkingStore(optLinkingAnnotationStoreDir.get()));
  } else {
    optLinkingAnnotationStore = Optional.absent();
  }
  return optLinkingAnnotationStore;
}
 
Example 9
Project: elastic-job-cloud   File: CloudJobConfigurationService.java   View Source Code Vote up 5 votes
/**
 * 获取所有注册的云作业配置.
 * 
 * @return 注册的云作业配置
 */
public Collection<CloudJobConfiguration> loadAll() {
    if (!regCenter.isExisted(CloudJobConfigurationNode.ROOT)) {
        return Collections.emptyList();
    }
    List<String> jobNames = regCenter.getChildrenKeys(CloudJobConfigurationNode.ROOT);
    Collection<CloudJobConfiguration> result = new ArrayList<>(jobNames.size());
    for (String each : jobNames) {
        Optional<CloudJobConfiguration> config = load(each);
        if (config.isPresent()) {
            result.add(config.get());
        }
    }
    return result;
}
 
Example 10
Project: n4js   File: NfarStorageMapper.java   View Source Code Vote up 5 votes
@Override
public boolean isRejected(IFolder folder) {
	if (isLibraryFolder(folder)) {
		return false;
	}
	Optional<? extends IN4JSSourceContainer> sourceContainerOpt = eclipseCore.create(folder);
	return !sourceContainerOpt.isPresent();
}
 
Example 11
Project: raml-java-tools   File: HandlerList.java   View Source Code Vote up 5 votes
@Override
public boolean handleSafely(final Node node, YamlEmitter emitter) throws IOException {

    Optional<NodeHandler<?>> handler = FluentIterable.from(handlerList).firstMatch(new Predicate<NodeHandler<? extends Node>>() {
        @Override
        public boolean apply(@Nullable NodeHandler<? extends Node> nodeHandler) {
            return nodeHandler.handles(node);
        }
    });

    return handler.isPresent() && handler.get().handle(node, emitter);

}
 
Example 12
Project: tac-kbp-eal   File: ScoringUtils.java   View Source Code Vote up 5 votes
static ScoringCorefID extractScoringEntity(EREArgument ea, EREDocument ereDoc) {
  if (ea instanceof EREEntityArgument) {
    final Optional<EREEntity> entityContainingMention = ereDoc.getEntityContaining(
        ((EREEntityArgument) ea).entityMention());
    if (entityContainingMention.isPresent()) {
      return new ScoringCorefID.Builder()
          .scoringEntityType(ScoringEntityType.fromCASType(
              EREAligner.getBestCASType(entityContainingMention.get())))
        .withinTypeID(entityContainingMention.get().getID()).build();
    } else {
      throw new TACKBPEALException("ERE mention not in any entity");
    }
  } else if (ea instanceof EREFillerArgument) {
    if (ea.getRole().equals("time")) {
      // in the 2016 guidelines we special case time to be resolved to its
      // TIME form
      final Optional<String> normalizedTime =
          ((EREFillerArgument) ea).filler().getNormalizedTime();
      if (normalizedTime.isPresent()) {
        return new ScoringCorefID.Builder().scoringEntityType(ScoringEntityType.Time)
          .withinTypeID(normalizedTime.get()).build();
      } else {
        throw new TACKBPEALException("Time argument has non-temporal filler");
      }
    } else {
      return new ScoringCorefID.Builder().scoringEntityType(ScoringEntityType.Filler)
        .withinTypeID(((EREFillerArgument) ea).filler().getID()).build();
    }
  } else {
    throw new TACKBPEALException("Unknown ERE argument type " + ea.getClass());
  }
}
 
Example 13
Project: SECP   File: UserDAO.java   View Source Code Vote up 5 votes
public Optional<User> getUserWithDevices(long id)
{
    Optional<User> optionalUser = find(id);
    if(optionalUser.isPresent())
        Hibernate.initialize(optionalUser.get().getDevices());

    return optionalUser;
}
 
Example 14
Project: GPigValidator   File: Validator.java   View Source Code Vote up 5 votes
protected static Optional<String> checkAnnotationConstraintError(Object objectToValidate, Field field,
                                                                 Annotation annotation) {
    try {
        field.setAccessible(true);

        Object fieldValue = field.get(objectToValidate);

        Optional<String> errorOpt = checkErrorInFieldForAnnotation(annotation, fieldValue);
        if (errorOpt.isPresent())
            return Optional.of(String.format("Field '%s' %s", field.getName(), errorOpt.get()));
        return errorOpt;
    } catch (IllegalArgumentException | IllegalAccessException e) {
        throw new InternalException(e);
    }
}
 
Example 15
Project: empiria.player   File: SourceListViewDropHandler.java   View Source Code Vote up 5 votes
@Override
public void onDrop(DropEvent event) {
    Optional<DragDataObject> objectFromEvent = objectFromEventExtractor.extractDroppedObjectFromEvent(event);
    if (objectFromEvent.isPresent()) {
        DragDataObject dataObject = objectFromEvent.get();
        sourceListPresenter.onDropEvent(dataObject.getItemId(), dataObject.getSourceId());
    }
}
 
Example 16
Project: CustomWorldGen   File: TRSRTransformation.java   View Source Code Vote up 5 votes
public Optional<TRSRTransformation> apply(Optional<? extends IModelPart> part)
{
    if(part.isPresent())
    {
        return Optional.absent();
    }
    return Optional.of(this);
}
 
Example 17
Project: verify-hub   File: AttributeQueryRequestClient.java   View Source Code Vote up 5 votes
public Element sendQuery(Element matchingServiceRequest, String messageId, SessionId sessionId, URI matchingServiceUri) {
    LOG.info("Sending attribute query to {}", matchingServiceUri);
    Optional<Element> response = sendSingleQuery(
            matchingServiceRequest,
            messageId,
            sessionId,
            matchingServiceUri
    );
    if (response.isPresent()) {
        return response.get();
    }
    throw new MatchingServiceException(format("Attribute query failed"));
}
 
Example 18
Project: tac-kbp-eal   File: KBP2015Scorer.java   View Source Code Vote up 5 votes
private void score(final AnnotationStore goldAnswerStore,
    final LinkingStore referenceLinkingStore, final ArgumentStore argumentStore,
    final LinkingStore systemLinkingStore, Set<Symbol> docsToScore, final File outputDir)
    throws IOException {

  final List<EALScorer2015Style.Result> perDocResults = Lists.newArrayList();

  for (final Symbol docID : docsToScore) {
    try {
      final AnswerKey argumentKey = goldAnswerStore.read(docID);
      final ArgumentOutput argumentOutput = argumentStore.readOrEmpty(docID);

      final Optional<ResponseLinking> referenceLinking = referenceLinkingStore.read(argumentKey);
      final Optional<ResponseLinking> systemLinking = systemLinkingStore.read(argumentOutput);

      if (!referenceLinking.isPresent()) {
        throw new RuntimeException("Reference linking missing for " + docID);
      }

      if (!systemLinking.isPresent()) {
        throw new RuntimeException("System linking missing for " + docID);
      }

      final ScoringData scoringData = ScoringData.builder()
          .answerKey(argumentKey)
          .argumentOutput(argumentOutput)
          .referenceLinking(referenceLinking.get())
          .systemLinking(systemLinking.get())
          .build();

      perDocResults.add(documentScorer.score(scoringData));
    } catch (Exception e) {
      throw new RuntimeException("Exception while processing " + docID, e);
    }
  }

  writeNormalOutput(perDocResults, outputDir);
  writeBootstrappedOutput(perDocResults, outputDir);
}
 
Example 19
Project: hashsdn-controller   File: ResolveDataChangeEventsTask.java   View Source Code Vote up 4 votes
/**
 * Resolves data change event for supplied node
 *
 * @param path
 *            Path to current node in tree
 * @param listeners
 *            Collection of Listener registration nodes interested in
 *            subtree
 * @param modification
 *            Modification of current node
 * @param before
 *            - Original (before) state of current node
 * @param after
 *            - After state of current node
 * @return True if the subtree changed, false otherwise
 */
private boolean resolveAnyChangeEvent(final ResolveDataChangeState state, final DataTreeCandidateNode node) {
    final Optional<NormalizedNode<?, ?>> maybeBefore = node.getDataBefore();
    final Optional<NormalizedNode<?, ?>> maybeAfter = node.getDataAfter();
    final ModificationType type = node.getModificationType();

    if (type != ModificationType.UNMODIFIED && !maybeAfter.isPresent() && !maybeBefore.isPresent()) {
        LOG.debug("Modification at {} has type {}, but no before- and after-data. Assuming unchanged.",
                state.getPath(), type);
        return false;
    }

    // no before and after state is present

    switch (type) {
    case SUBTREE_MODIFIED:
        return resolveSubtreeChangeEvent(state, node);
    case APPEARED:
    case WRITE:
        Preconditions.checkArgument(maybeAfter.isPresent(),
                "Modification at {} has type {} but no after-data", state.getPath(), type);
        if (!maybeBefore.isPresent()) {
            @SuppressWarnings({ "unchecked", "rawtypes" })
            final NormalizedNode<PathArgument, ?> afterNode = (NormalizedNode)maybeAfter.get();
            resolveSameEventRecursivelly(state, afterNode, DOMImmutableDataChangeEvent.getCreateEventFactory());
            return true;
        }

        return resolveReplacedEvent(state, maybeBefore.get(), maybeAfter.get());
    case DISAPPEARED:
    case DELETE:
        Preconditions.checkArgument(maybeBefore.isPresent(),
                "Modification at {} has type {} but no before-data", state.getPath(), type);

        @SuppressWarnings({ "unchecked", "rawtypes" })
        final NormalizedNode<PathArgument, ?> beforeNode = (NormalizedNode)maybeBefore.get();
        resolveSameEventRecursivelly(state, beforeNode, DOMImmutableDataChangeEvent.getRemoveEventFactory());
        return true;
    case UNMODIFIED:
        return false;
    }

    throw new IllegalStateException(String.format("Unhandled node state %s at %s", type, state.getPath()));
}
 
Example 20
Project: elastic-job-cloud   File: FacadeService.java   View Source Code Vote up 2 votes
/**
 * 判断作业是否被禁用.
 * 
 * @param jobName 作业名称
 * @return 作业是否被禁用
 */
public boolean isJobDisabled(final String jobName) {
    Optional<CloudJobConfiguration> jobConfiguration = jobConfigService.load(jobName);
    return !jobConfiguration.isPresent() || disableAppService.isDisabled(jobConfiguration.get().getAppName()) || disableJobService.isDisabled(jobName);
}