当前位置: 首页>>代码示例>>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;未经允许,请勿转载。