Java 类com.google.common.base.Optional 实例源码

项目:verify-hub    文件:Cycle3MatchRequestSentStateController.java   
private AttributeQueryRequestDto createAttributeQuery(List<UserAccountCreationAttribute> userAccountCreationAttributes) {
    MatchingServiceConfigEntityDataDto matchingServiceConfig = matchingServiceConfigProxy.getMatchingService(state.getMatchingServiceAdapterEntityId());

    return AttributeQueryRequestDto.createUserAccountRequiredMatchingServiceRequest(
            state.getRequestId(),
            state.getEncryptedMatchingDatasetAssertion(),
            state.getAuthnStatementAssertion(),
            Optional.<Cycle3Dataset>absent(),
            state.getRequestIssuerEntityId(),
            state.getAssertionConsumerServiceUri(),
            state.getMatchingServiceAdapterEntityId(),
            DateTime.now().plus(policyConfiguration.getMatchingServiceResponseWaitPeriod()),
            state.getIdpLevelOfAssurance(),
            userAccountCreationAttributes,
            state.getPersistentId(),
            assertionRestrictionFactory.getAssertionExpiry(),
            matchingServiceConfig.getUserAccountCreationUri(),
            matchingServiceConfig.isOnboarding()
    );
}
项目:dotwebstack-framework    文件:ArraySchemaMapperTest.java   
@Test
public void mapGraphValue_ReturnsEmptyResult_WhenNoValueHasBeenDefined() {
  // Arrange
  Value value = null;

  // Act
  Object result = schemaMapperAdapter.mapGraphValue(arrayProperty, contextMock,
      ValueContext.builder().value(value).build(), schemaMapperAdapter);

  // Assert
  assertThat(result, instanceOf(List.class));

  List<Optional<String>> list = (List) result;

  assertThat(list, empty());
}
项目:verify-hub    文件:EidasAttributeQueryRequestDtoBuilder.java   
public EidasAttributeQueryRequestDto build() {
    return new EidasAttributeQueryRequestDto(
        "requestId",
        "authnRequestIssuesEntityId",
        URI.create("assertionConsumerServiceUri"),
        DateTime.now().plusHours(2),
        "matchingServiceAdapterEntityId",
        URI.create("matchingServiceAdapterUri"),
        DateTime.now().plusHours(1),
        true,
        LevelOfAssurance.LEVEL_2,
        new PersistentId("nameId"),
        Optional.of(aCycle3Dataset()),
        Optional.absent(),
        "encryptedIdentityAssertion"
    );
}
项目:SECP    文件:GroupControllerTest.java   
@Test
public void testGetGroupsForUsers()
{
    User user = new User();
    Group group = new Group();
    group.setId(GROUPID);
    Set<Group> groups = new HashSet<>();
    Set<GroupDTO> groupDTOS = new HashSet<>();
    groupDTOS.add(getGroupResponse());
    groups.add(group);
    user.setGroups(groups);
    Mockito.when(userDAO.getUserWithGroups(Matchers.anyLong())).thenReturn(Optional.fromNullable(user));
    Response response = controller.getGroupsForUser(user);
    Response validResponse = Response.status(Response.Status.OK).entity(groupDTOS).build();
    assertEquals(response.getStatus(), validResponse.getStatus());
    assertEquals(response.getEntity(),  validResponse.getEntity());
}
项目:verify-hub    文件:UserAccountCreationRequestSentStateControllerTest.java   
@Test
public void getNextState_shouldMaintainRelayState() throws Exception {
    final String relayState = "4x100m";
    UserAccountCreationRequestSentState state = aUserAccountCreationRequestSentState()
            .withRelayState(Optional.of(relayState))
            .build();
    UserAccountCreationRequestSentStateController controller =
            new UserAccountCreationRequestSentStateController(state, null, eventSinkHubEventLogger, null, levelOfAssuranceValidator, null, null);

    UserAccountCreatedFromMatchingService userAccountCreatedFromMatchingService = new UserAccountCreatedFromMatchingService("issuer-id", "", "", Optional.<LevelOfAssurance>absent());

    final State newState = controller.getNextStateForUserAccountCreated(userAccountCreatedFromMatchingService);
    assertThat(newState).isInstanceOf(UserAccountCreatedState.class);

    final UserAccountCreatedState userAccountCreatedState = (UserAccountCreatedState)newState;
    assertThat(userAccountCreatedState.getRelayState()).isNotNull();
    assertThat(userAccountCreatedState.getRelayState().isPresent()).isTrue();
    assertThat(userAccountCreatedState.getRelayState().get()).isEqualTo(relayState);

}
项目:Mastering-Apache-Storm    文件:BingMapsLookup.java   
/**
 * Gets the State of the Tweet by checking the InputStream.
 * For a sample Bing Maps API response, please check the snippet at the end of this file.
 *
 * @param inputStream Bing Maps API response.
 * @return State of the Tweet as got from Bing Maps API reponse.
 */
@SuppressWarnings("unchecked")
private final static Optional<String> getStateFromJSONResponse(InputStream inputStream) {
    final ObjectMapper mapper = new ObjectMapper();
    try {
        //final Map<String,Object> bingResponse = (Map<String, Object>) mapper.readValue(new File("C:/BingMaps_JSON_Response.json"), Map.class);
        final Map<String,Object> bingResponse = (Map<String, Object>) mapper.readValue(inputStream, Map.class);
        if(200 == Integer.parseInt(String.valueOf(bingResponse.get("statusCode")))) {
            final List<Map<String, Object>> resourceSets = (List<Map<String, Object>>) bingResponse.get("resourceSets");
            if(resourceSets != null && resourceSets.size() > 0){
                final List<Map<String, Object>> resources = (List<Map<String, Object>>) resourceSets.get(0).get("resources");
                if(resources != null && resources.size() > 0){
                    final Map<String, Object> address = (Map<String, Object>) resources.get(0).get("address");
                    LOGGER.debug("State==>{}", address.get("adminDistrict"));
                    return Optional.of((String) address.get("adminDistrict"));
                }
            }
        }
    } catch (final IOException ioException) {
        LOGGER.error(ioException.getMessage(), ioException);
        ioException.printStackTrace();
    }
    return Optional.absent();
}
项目:CustomWorldGen    文件:EntityItemFrame.java   
private void setDisplayedItemWithUpdate(@Nullable ItemStack stack, boolean p_174864_2_)
{
    if (stack != null)
    {
        stack = stack.copy();
        stack.stackSize = 1;
        stack.setItemFrame(this);
    }

    this.getDataManager().set(ITEM, Optional.fromNullable(stack));
    this.getDataManager().setDirty(ITEM);

    if (stack != null)
    {
        this.playSound(SoundEvents.ENTITY_ITEMFRAME_ADD_ITEM, 1.0F, 1.0F);
    }

    if (p_174864_2_ && this.hangingPosition != null)
    {
        this.worldObj.updateComparatorOutputLevel(this.hangingPosition, Blocks.AIR);
    }
}
项目:n4js    文件:NfarStorageMapper.java   
@Override
public void initializeCache() {
    Optional<? extends IN4JSEclipseProject> projectOpt = null;
    IN4JSEclipseProject n4jsProject = null;
    for (IProject project : workspace.getRoot().getProjects()) {
        projectOpt = eclipseCore.create(project);
        if (projectOpt.isPresent()) {
            n4jsProject = projectOpt.get();
            if (n4jsProject.exists()) {
                updateCache(n4jsProject);
            }
        }
    }
    Listener listener = new Listener();
    workspace.addResourceChangeListener(listener, IResourceChangeEvent.POST_CHANGE);
}
项目:hashsdn-controller    文件:RpcFacade.java   
public Element toXml(final Document doc, final Object result, final OperationExecution execution)
        throws DocumentedException {
    AttributeMappingStrategy<?, ? extends OpenType<?>> mappingStrategy = new ObjectMapper()
            .prepareStrategy(execution.getReturnType());
    Optional<?> mappedAttributeOpt = mappingStrategy.mapAttribute(result);
    Preconditions.checkState(mappedAttributeOpt.isPresent(), "Unable to map return value %s as %s", result,
            execution.getReturnType().getOpenType());

    // FIXME: multiple return values defined as leaf-list and list in yang should
    // not be wrapped in output xml element,
    // they need to be appended directly under rpc-reply element
    //
    // Either allow List of Elements to be returned from NetconfOperation or
    // pass reference to parent output xml element for netconf operations to
    // append result(s) on their own
    Element tempParent = XmlUtil.createElement(doc, "output",
            Optional.of(XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
    new ObjectXmlWriter().prepareWritingStrategy(execution.getReturnType().getAttributeYangName(),
            execution.getReturnType(), doc)
            .writeElement(tempParent, execution.getNamespace(), mappedAttributeOpt.get());

    XmlElement xmlElement = XmlElement.fromDomElement(tempParent);
    return xmlElement.getChildElements().size() > 1 ? tempParent : xmlElement.getOnlyChildElement().getDomElement();
}
项目:GitHub    文件:Proto.java   
@Value.Lazy
public Optional<ValueImmutableInfo> features() {
  Optional<ValueImmutableInfo> immutableAnnotation =
      ImmutableMirror.find(element()).transform(ToImmutableInfo.FUNCTION);

  if (immutableAnnotation.isPresent()) {
    return immutableAnnotation;
  }

  for (String a : environment().round().customImmutableAnnotations()) {
    if (isAnnotatedWith(element(), a)) {
      return Optional.of(environment().defaultStyles().defaults());
    }
  }

  return Optional.absent();
}
项目:verify-hub    文件:EidasAttributeQueryRequestDtoBuilderTest.java   
@Test
public void build() throws Exception {
    Map<String, String> map = new HashMap<>();
    map.put("attribute", "attributeValue");

    EidasAttributeQueryRequestDto eidasAttributeQueryRequestDto = EidasAttributeQueryRequestDtoBuilder.anEidasAttributeQueryRequestDto().build();

    assertThat(eidasAttributeQueryRequestDto.getRequestId()).isEqualTo("requestId");
    assertThat(eidasAttributeQueryRequestDto.getPersistentId()).isEqualTo(new PersistentId("nameId"));
    assertThat(eidasAttributeQueryRequestDto.getEncryptedIdentityAssertion()).isEqualTo("encryptedIdentityAssertion");
    assertThat(eidasAttributeQueryRequestDto.getAssertionConsumerServiceUri()).isEqualTo(URI.create("assertionConsumerServiceUri"));
    assertThat(eidasAttributeQueryRequestDto.getAuthnRequestIssuerEntityId()).isEqualTo("authnRequestIssuesEntityId");
    assertThat(eidasAttributeQueryRequestDto.getLevelOfAssurance()).isEqualTo(LevelOfAssurance.LEVEL_2);
    assertThat(eidasAttributeQueryRequestDto.getAttributeQueryUri()).isEqualTo(URI.create("matchingServiceAdapterUri"));
    assertThat(eidasAttributeQueryRequestDto.getMatchingServiceEntityId()).isEqualTo("matchingServiceAdapterEntityId");
    assertThat(eidasAttributeQueryRequestDto.getMatchingServiceRequestTimeOut()).isEqualTo(DateTime.now().plusHours(1));
    assertThat(eidasAttributeQueryRequestDto.isOnboarding()).isTrue();
    assertThat(eidasAttributeQueryRequestDto.getCycle3Dataset()).isEqualTo(Optional.of(new Cycle3Dataset(map)));
    assertThat(eidasAttributeQueryRequestDto.getUserAccountCreationAttributes()).isEqualTo(Optional.absent());
    assertThat(eidasAttributeQueryRequestDto.getAssertionExpiry()).isEqualTo(DateTime.now().plusHours(2));
}
项目:guava-mock    文件:MoreFiles.java   
@Override
public Optional<Long> sizeIfKnown() {
  BasicFileAttributes attrs;
  try {
    attrs = readAttributes();
  } catch (IOException e) {
    // Failed to get attributes; we don't know the size.
    return Optional.absent();
  }

  // Don't return a size for directories or symbolic links; their sizes are implementation
  // specific and they can't be read as bytes using the read methods anyway.
  if (attrs.isDirectory() || attrs.isSymbolicLink()) {
    return Optional.absent();
  }

  return Optional.of(attrs.size());
}
项目:n4js    文件:RuntimeEnvironmentsHelper.java   
private void recursiveCollectRlFromChain(IN4JSProject runtimeEnvironment, Collection<IN4JSProject> collection) {
    Optional<String> extended = runtimeEnvironment.getExtendedRuntimeEnvironmentId();
    if (extended.isPresent()) {
        String id = extended.get();
        List<IN4JSProject> extendedRE = from(getAllProjects()).filter(p -> id.equals(p.getProjectId()))
                .toList();

        if (extendedRE.isEmpty()) {
            return;
        }

        if (extendedRE.size() > 1) {
            LOGGER.debug("multiple projects match id " + id);
            LOGGER.error(new RuntimeException("Cannot obtain transitive list of provided libraries"));
            return;
        }

        IN4JSProject extendedRuntimeEnvironemnt = extendedRE.get(0);
        recursiveProvidedRuntimeLibrariesCollector(extendedRuntimeEnvironemnt.getProvidedRuntimeLibraries(),
                collection, p -> isRuntimeLibrary(p));

        recursiveCollectRlFromChain(extendedRuntimeEnvironemnt, collection);

    }
}
项目:verify-hub    文件:ReceivedAuthnRequest.java   
public ReceivedAuthnRequest(
        String id,
        String issuer,
        DateTime issueInstant,
        Optional<Boolean> forceAuthentication,
        URI assertionConsumerServiceUri,
        Optional<String> relayState,
        DateTime receivedTime,
        String principalIpAddress) {

    this.id = id;
    this.issuer = issuer;
    this.issueInstant = issueInstant;
    this.forceAuthentication = forceAuthentication;
    this.assertionConsumerServiceUri = assertionConsumerServiceUri;
    this.relayState = relayState;
    this.receivedTime = receivedTime;
    this.principalIpAddress = principalIpAddress;
}
项目:n4js    文件:NfarStorageMapper.java   
@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();
    }
}
项目:tac-kbp-eal    文件:ScoreKBPAgainstERE.java   
private DocLevelEventArg resolveToERE(final EREDocument doc, final EREAligner ereAligner,
    final Response response) {
  numResponses.add(errKey(response));
  final Symbol realis = Symbol.from(response.realis().name());

  final Optional<ScoringCorefID> alignedCorefIDOpt = ereAligner.argumentForResponse(response);
  if (!alignedCorefIDOpt.isPresent()) {
    log.info("Alignment failed for {}", response);
    mentionAlignmentFailuresB.put(errKey(response), response.toString());
  }

  // this increments the alignment failure ID regardless of success or failure, but
  // we don't care
  final ScoringCorefID alignedCorefID = alignedCorefIDOpt.or(
      // in case of alignment failure, we make a pseudo-entity from the CAS offsets
      // it will always be wrong, but will be consistent for the same extent appearing in
      // different event roles
      new ScoringCorefID.Builder().scoringEntityType(ScoringEntityType.AlignmentFailure)
      .withinTypeID(response.canonicalArgument().charOffsetSpan().asCharOffsetRange().toString())
      .build());

  return new DocLevelEventArg.Builder().docID(Symbol.from(doc.getDocId()))
      .eventType(response.type()).eventArgumentType(response.role())
      .corefID(alignedCorefID.globalID()).realis(realis).build();
}
项目:n4js    文件:N4JSAllContainersState.java   
private void tryValidateManifest(final IResourceDelta delta) {
    final String fullPath = delta.getFullPath().toString();
    final URI folderUri = URI.createPlatformResourceURI(fullPath, true);
    final IN4JSProject project = core.findProject(folderUri).orNull();
    if (null != project && project.exists()) {
        final URI manifestLocation = project.getManifestLocation().orNull();
        if (null != manifestLocation) {
            final IFile manifest = delta.getResource().getProject().getFile(N4MF_MANIFEST);
            final ResourceSet resourceSet = core.createResourceSet(Optional.of(project));
            final Resource resource = resourceSet.getResource(manifestLocation, true);
            final Job job = Job.create("", monitor -> {
                validatorExtension.updateValidationMarkers(manifest, resource, ALL, monitor);
                return OK_STATUS;
            });
            job.setPriority(INTERACTIVE);
            job.schedule();
        }
    }
}
项目:satisfy    文件:SatisfyAnnotatedStepDescription.java   
private Optional<String> getCompatibleStepNameFrom(Method testMethod) {
    Annotation[] annotations = testMethod.getAnnotations();
    for (Annotation annotation : annotations) {
        if (isACompatibleStep(annotation)) {
            try {
                String annotationType = annotation.annotationType()
                        .getSimpleName();
                String annotatedValue = (String) annotation.getClass()
                        .getMethod("value").invoke(annotation);
                if (StringUtils.isEmpty(annotatedValue)) {
                    return Optional.absent();
                } else {
                    return Optional.of(annotationType + " " + StringUtils
                            .uncapitalize(annotatedValue));
                }

            } catch (Exception ignoredException) {
            }
        }
    }
    return Optional.absent();
}
项目:redirector    文件:FlavorRuleToTestConverter.java   
private TestSuiteResponse obtainExpectedResponse(IfExpression rule) {
    TestSuiteResponse response = new TestSuiteResponse();

    for (Expressions expressions : RulesUtils.getReturn(rule)) {
        if (expressions instanceof Server) {
            Optional<String> path = Optional.fromNullable(((Server) expressions).getPath());
            if (path.or("").contains("/")) {
                XreStackPath stackPath = new XreStackPath(path.get() + "/" + serviceName);
                response.setFlavor(stackPath.getFlavor());
                response.setXreStack(stackPath.getStackOnlyPath());
            } else {
                response.setFlavor(path.or(""));
            }
            response.setRule(rule.getId());

            return response;
        } else {
            log.warn("Rule {} is skipped. ServerGroup is not supported", rule.getId());
        }
    }

    return null;
}
项目:hashsdn-controller    文件:RaftActorServerConfigurationSupportTest.java   
@Test
public void testRemoveServerForwardToLeader() {
    LOG.info("testRemoveServerForwardToLeader starting");

    DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
    configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));

    ActorRef leaderActor = actorFactory.createTestActor(
            MessageCollectorActor.props(), actorFactory.generateActorId(LEADER_ID));

    TestActorRef<MockRaftActor> followerRaftActor = actorFactory.createTestActor(
            MockRaftActor.builder().id(FOLLOWER_ID).peerAddresses(ImmutableMap.of(LEADER_ID,
                    leaderActor.path().toString())).config(configParams).persistent(Optional.of(false))
                    .props().withDispatcher(Dispatchers.DefaultDispatcherId()),
            actorFactory.generateActorId(FOLLOWER_ID));
    followerRaftActor.underlyingActor().waitForInitializeBehaviorComplete();

    followerRaftActor.tell(new AppendEntries(1, LEADER_ID, 0, 1, Collections.<ReplicatedLogEntry>emptyList(),
            -1, -1, (short)0), leaderActor);

    followerRaftActor.tell(new RemoveServer(FOLLOWER_ID), testKit.getRef());
    expectFirstMatching(leaderActor, RemoveServer.class);

    LOG.info("testRemoveServerForwardToLeader ending");
}
项目:verify-hub    文件:EidasCycle3DataResourceTest.java   
@Test
public void shouldGetCycle3AttributeRequestDataFromConfiguration() throws JsonProcessingException {
    final SessionId sessionId = SessionIdBuilder.aSessionId().build();
    final String rpEntityId = new EidasCycle3DTO(sessionId).getRequestIssuerEntityId();
    final Response sessionCreatedResponse = createSessionInEidasAwaitingCycle3DataState(sessionId);
    assertThat(sessionCreatedResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());

    final MatchingProcessDto cycle3Attribute = new MatchingProcessDto(Optional.of("TUFTY_CLUB_CARD"));
    configStub.setUpStubForEnteringAwaitingCycle3DataState(rpEntityId, cycle3Attribute);
    samlSoapProxyProxyStub.setUpStubForSendHubMatchingServiceRequest(sessionId);

    final Cycle3AttributeRequestData actualResponse = getCycle3Data(sessionId);

    final Cycle3AttributeRequestData expectedResponse = aCycle3AttributeRequestData()
        .withAttributeName(cycle3Attribute.getAttributeName().get())
        .withRequestIssuerId(rpEntityId)
        .build();
    assertThat(actualResponse).isEqualToComparingFieldByField(expectedResponse);
}
项目:hashsdn-controller    文件:ShardDataTreeTest.java   
private static NormalizedNode<?, ?> getCars(final ShardDataTree shardDataTree) {
    final ReadOnlyShardDataTreeTransaction readOnlyShardDataTreeTransaction =
            shardDataTree.newReadOnlyTransaction(nextTransactionId());
    final DataTreeSnapshot snapshot1 = readOnlyShardDataTreeTransaction.getSnapshot();

    final Optional<NormalizedNode<?, ?>> optional = snapshot1.readNode(CarsModel.BASE_PATH);

    assertEquals(true, optional.isPresent());

    return optional.get();
}
项目:webmate-sdk-java    文件:JobEngine.java   
private Optional<JobRunId> getFirstJobRunForJob(JobId jobId) {
    for (int i = 0; i < 10; ++i) {
        List<JobRunId> jobRunIds = this.apiClient.getJobRunsForJob(jobId);
        if (jobRunIds.size() > 0) {
            return Optional.of(jobRunIds.get(0));
        }
    }
    return Optional.absent();
}
项目:HCFCore    文件:PlayerJoinedFactionEvent.java   
/**
 * Gets the optional {@link Player} joining, this will load lazily.
 *
 * @return the {@link Player} or {@link Optional#absent()} or if offline
 */
public Optional<Player> getPlayer() {
    if (this.player == null) {
        this.player = Optional.fromNullable(Bukkit.getPlayer(this.playerUUID));
    }

    return this.player;
}
项目:SECP    文件:AdminController.java   
private User getUserFromID(String userID) {
    long id = Long.parseLong(userID);

    Optional<User> user = userDAO.find(id);

    if (!user.isPresent()) {
        String error = String.format(AdminErrorMessage.DOES_NOT_EXIST, userErrorString);
        throw new WebApplicationException(error, Response.Status.BAD_REQUEST);
    }

    return user.get();
}
项目:verify-hub    文件:SamlMessageSenderHandler.java   
public SamlMessage generateAuthnResponseFromHub(SessionId sessionId, String principalIpAddressAsSeenByHub) {
    AuthnResponseFromHubContainerDto authnResponseFromHub = sessionProxy.getAuthnResponseFromHub(sessionId);
    Response samlResponse = responseTransformer.apply(authnResponseFromHub.getSamlResponse());
    validateAndLogSamlResponseSignature(samlResponse);
    SamlMessage samlMessage = new SamlMessage(authnResponseFromHub.getSamlResponse(), SamlMessageType.SAML_RESPONSE, authnResponseFromHub.getRelayState(), authnResponseFromHub.getPostEndpoint().toString(), Optional.<Boolean>absent());
    externalCommunicationEventLogger.logResponseFromHub(samlResponse.getID(), sessionId, authnResponseFromHub.getPostEndpoint(), principalIpAddressAsSeenByHub);
    return samlMessage;
}
项目:ArchUnit    文件:MessageAssertionChain.java   
public Result build(List<String> lines) {
    boolean matches = true;
    List<String> remainingLines = new ArrayList<>(lines);
    Optional<String> mismatchDescription = Optional.absent();
    for (Link link : subLinks) {
        Result result = link.filterMatching(remainingLines);
        matches = matches && result.matches;
        remainingLines = result.remainingLines;
        mismatchDescription = append(mismatchDescription, result.mismatchDescription);
    }
    return new Result(matches, remainingLines, mismatchDescription);
}
项目:verify-hub    文件:LevelOfAssuranceValidatorTest.java   
@Test
public void validate_shouldThrowExceptionIfLevelOfAssuranceFromMatchingServiceDoesNotExist() throws Exception {
    LevelOfAssurance levelOfAssurance = LevelOfAssurance.LEVEL_2;
    try {
        levelOfAssuranceValidator.validate(Optional.<LevelOfAssurance>absent(), levelOfAssurance);
        fail("fail");
    } catch (StateProcessingValidationException e) {
        assertThat(e.getMessage()).isEqualTo(StateProcessingValidationException.noLevelOfAssurance().getMessage());
    }
}
项目:hashsdn-controller    文件:ShardDataChangeListenerPublisherActorProxy.java   
@Override
public void registerDataChangeListener(YangInstanceIdentifier path,
        AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener, DataChangeScope scope,
        Optional<DataTreeCandidate> initialState,
        Consumer<ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>>
            onRegistration) {
    publisherActor().tell(new ShardDataChangePublisherActor.RegisterListener(path, listener, scope, initialState,
            onRegistration), ActorRef.noSender());
}
项目:googles-monorepo-demo    文件:BinaryTreeTraverser.java   
/**
 * Returns the children of this node, in left-to-right order.
 */
@Override
public final Iterable<T> children(final T root) {
  checkNotNull(root);
  return new FluentIterable<T>() {
    @Override
    public Iterator<T> iterator() {
      return new AbstractIterator<T>() {
        boolean doneLeft;
        boolean doneRight;

        @Override
        protected T computeNext() {
          if (!doneLeft) {
            doneLeft = true;
            Optional<T> left = leftChild(root);
            if (left.isPresent()) {
              return left.get();
            }
          }
          if (!doneRight) {
            doneRight = true;
            Optional<T> right = rightChild(root);
            if (right.isPresent()) {
              return right.get();
            }
          }
          return endOfData();
        }
      };
    }

    @Override
    public void forEach(Consumer<? super T> action) {
      acceptIfPresent(action, leftChild(root));
      acceptIfPresent(action, rightChild(root));
    }
  };
}
项目:SECP    文件:UserResourceTest.java   
@Test
public void testIsUserAnAdminWithInvalidID()
{
    long id = 12;
    Optional<User> user = Optional.of(new User());
    Mockito.when(userDAO.find(id)).thenReturn(user);
    Response response = resources.client().target(isUserAnAdminUrl + id).request().get();
    ResponseValidator.validate(response, 204);
}
项目:dremio-oss    文件:AccelerationUtils.java   
public static Iterable<Layout> allLayouts(final Acceleration acceleration) {
  final LayoutContainer aggContainer = Optional.fromNullable(acceleration.getAggregationLayouts()).or(EMPTY_CONTAINER);
  final LayoutContainer rawContainer = Optional.fromNullable(acceleration.getRawLayouts()).or(EMPTY_CONTAINER);

  final Iterable<Layout> aggLayouts = AccelerationUtils.selfOrEmpty(aggContainer.getLayoutList());
  final Iterable<Layout> rawLayouts = AccelerationUtils.selfOrEmpty(rawContainer.getLayoutList());

  return Iterables.concat(aggLayouts, rawLayouts);
}
项目:HCFCore    文件:PlayerJoinFactionEvent.java   
public Optional<Player> getPlayer() {
    if (this.player == null) {
        this.player = Optional.fromNullable(Bukkit.getPlayer(this.playerUUID));
    }

    return this.player;
}
项目:verify-hub    文件:SamlProxyApplicationExceptionMapperTest.java   
@Test
public void toResponse_shouldAuditException() throws Exception {
    URI exceptionUri = URI.create("/exception-uri");
    ApplicationException exception = createUnauditedException(exceptionType, errorId, exceptionUri);

    mapper.toResponse(exception);

    verify(exceptionAuditor).auditException(exception, Optional.of(sessionId));
}
项目:Elasticsearch    文件:QualifiedName.java   
/**
 * For an identifier of the form "a.b.c.d", returns "a.b.c"
 * For an identifier of the form "a", returns absent
 */
public Optional<QualifiedName> getPrefix()
{
    if (parts.size() == 1) {
        return Optional.absent();
    }

    return Optional.of(QualifiedName.of(parts.subList(0, parts.size() - 1)));
}
项目:Mods    文件:EntityBuilding.java   
public void setOwner(EntityLivingBase owner) {
    // TODO Auto-generated method stub
    this.owner = owner;
    if (owner instanceof EntityPlayer){
        this.ownerName = owner.getName();
        this.dataManager.set(OWNER_UUID, Optional.of(owner.getUniqueID()));
        this.enablePersistence();
    }
    else if(owner != null)
        this.engMade = true;
}
项目:dremio-oss    文件:MaterializationTask.java   
/**
 * The new materialization is only as fresh as the most stale input materialization. This method finds which of the
 * input materializations has the earliest expiration. The new materialization's expiration must be equal to or sooner
 * than this.
 * @return the earliest expiration. if no accelerations, Long.MAX_VALUE is returned
 */
private Optional<Long> getFirstExpiration() {
  if (jobRef.get().getJobAttempt().getInfo().getAcceleration() == null) {
    return Optional.absent();
  }
  List<Substitution> substitutions = jobRef.get().getJobAttempt().getInfo().getAcceleration().getSubstitutionsList();
  if (substitutions == null || substitutions.isEmpty()) {
    return Optional.absent();
  }
  return Optional.of(FluentIterable.from(substitutions)
    .transform(new Function<Substitution, Long>() {
      @Nullable
      @Override
      public Long apply(Substitution substitution) {
        List<String> path = substitution.getTablePathList();
        final String layoutId = path.get(1);
        assert layoutId.equals(substitution.getId().getLayoutId()) : String.format("Layouts not equal. Layout id1: %s, Layout id2: %s", layoutId, substitution.getId().getLayoutId());
        final String materializationId = path.get(2);
        List<Materialization> materializationList = context.materializationStore.get(new LayoutId(layoutId)).get().getMaterializationList();
        Materialization materialization = Iterables.find(materializationList, new Predicate<Materialization>() {
          @Override
          public boolean apply(@Nullable Materialization materialization) {
            return materialization.getId().getId().equals(materializationId);
          }
        }, null);
        if (materialization == null || materialization.getExpiration() == null) {
          return 0L;
        }
        return materialization.getExpiration();
      }
    })
    .toSortedList(new Comparator<Long>() {
      @Override
      public int compare(Long o1, Long o2) {
        return o1.compareTo(o2);
      }
    })
    .get(0)); // the list is guaranteed to be non-empty because of check at beginning of method.
}
项目:empiria.player    文件:MaximizedStickieSizeStorageJUnitTest.java   
@Test
public void shouldUpdateIfDimensionsBiggerThanCurrentlyStored() throws Exception {
    int colorIndex = 0;
    maximizedStickieSizeStorage.updateIfBiggerThanExisting(colorIndex, new StickieSize(111, 222));
    maximizedStickieSizeStorage.updateIfBiggerThanExisting(colorIndex, new StickieSize(333, 444));

    Optional<StickieSize> optionalStickieSize = maximizedStickieSizeStorage.getSizeOfMaximizedStickie(colorIndex);
    assertSizes(optionalStickieSize, 333, 444);
}
项目:empiria.player    文件:SimulationCanvasProviderTest.java   
@Test
public void testGetSimulationCanvas_canvasIsNull() {
    // given
    when(createJsLoader.getContent()).thenReturn(createJsContent);
    // when
    Optional<Element> simulationElemrnt = simulationCanvasProvider.getSimulationCanvasElement(createJsLoader);
    // then
    assertFalse(simulationElemrnt.isPresent());
}
项目:dremio-oss    文件:ChainExecutor.java   
private void saveLayoutMaterializationFailedState(Layout layout) {
  Optional<MaterializedLayout>  materializedLayoutOpt = context.getMaterializationStore().get(layout.getId());
  if (materializedLayoutOpt.isPresent()) {
    MaterializedLayout materializedLayout = materializedLayoutOpt.get();
    materializedLayout.setState(MaterializedLayoutState.FAILED);
    context.getMaterializationStore().save(materializedLayout);
  }
}