當前位置: 首頁>>代碼示例>>Java>>正文


Java Optional類代碼示例

本文整理匯總了Java中com.google.common.base.Optional的典型用法代碼示例。如果您正苦於以下問題:Java Optional類的具體用法?Java Optional怎麽用?Java Optional使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Optional類屬於com.google.common.base包,在下文中一共展示了Optional類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: createAttributeQuery

import com.google.common.base.Optional; //導入依賴的package包/類
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()
    );
}
 
開發者ID:alphagov,項目名稱:verify-hub,代碼行數:21,代碼來源:Cycle3MatchRequestSentStateController.java

示例2: mapGraphValue_ReturnsEmptyResult_WhenNoValueHasBeenDefined

import com.google.common.base.Optional; //導入依賴的package包/類
@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());
}
 
開發者ID:dotwebstack,項目名稱:dotwebstack-framework,代碼行數:17,代碼來源:ArraySchemaMapperTest.java

示例3: build

import com.google.common.base.Optional; //導入依賴的package包/類
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"
    );
}
 
開發者ID:alphagov,項目名稱:verify-hub,代碼行數:18,代碼來源:EidasAttributeQueryRequestDtoBuilder.java

示例4: testGetGroupsForUsers

import com.google.common.base.Optional; //導入依賴的package包/類
@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());
}
 
開發者ID:tosinoni,項目名稱:SECP,代碼行數:18,代碼來源:GroupControllerTest.java

示例5: getNextState_shouldMaintainRelayState

import com.google.common.base.Optional; //導入依賴的package包/類
@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);

}
 
開發者ID:alphagov,項目名稱:verify-hub,代碼行數:21,代碼來源:UserAccountCreationRequestSentStateControllerTest.java

示例6: getStateFromJSONResponse

import com.google.common.base.Optional; //導入依賴的package包/類
/**
 * 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();
}
 
開發者ID:PacktPublishing,項目名稱:Mastering-Apache-Storm,代碼行數:31,代碼來源:BingMapsLookup.java

示例7: setDisplayedItemWithUpdate

import com.google.common.base.Optional; //導入依賴的package包/類
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);
    }
}
 
開發者ID:F1r3w477,項目名稱:CustomWorldGen,代碼行數:23,代碼來源:EntityItemFrame.java

示例8: initializeCache

import com.google.common.base.Optional; //導入依賴的package包/類
@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);
}
 
開發者ID:eclipse,項目名稱:n4js,代碼行數:17,代碼來源:NfarStorageMapper.java

示例9: toXml

import com.google.common.base.Optional; //導入依賴的package包/類
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();
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:25,代碼來源:RpcFacade.java

示例10: features

import com.google.common.base.Optional; //導入依賴的package包/類
@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();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:18,代碼來源:Proto.java

示例11: build

import com.google.common.base.Optional; //導入依賴的package包/類
@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));
}
 
開發者ID:alphagov,項目名稱:verify-hub,代碼行數:22,代碼來源:EidasAttributeQueryRequestDtoBuilderTest.java

示例12: sizeIfKnown

import com.google.common.base.Optional; //導入依賴的package包/類
@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());
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:19,代碼來源:MoreFiles.java

示例13: recursiveCollectRlFromChain

import com.google.common.base.Optional; //導入依賴的package包/類
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);

	}
}
 
開發者ID:eclipse,項目名稱:n4js,代碼行數:26,代碼來源:RuntimeEnvironmentsHelper.java

示例14: ReceivedAuthnRequest

import com.google.common.base.Optional; //導入依賴的package包/類
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;
}
 
開發者ID:alphagov,項目名稱:verify-hub,代碼行數:20,代碼來源:ReceivedAuthnRequest.java

示例15: getStorages

import com.google.common.base.Optional; //導入依賴的package包/類
@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();
	}
}
 
開發者ID:eclipse,項目名稱:n4js,代碼行數:18,代碼來源:NfarStorageMapper.java


注:本文中的com.google.common.base.Optional類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。