Example usage for java.util Optional get

List of usage examples for java.util Optional get

Introduction

In this page you can find the example usage for java.util Optional get.

Prototype

public T get() 

Source Link

Document

If a value is present, returns the value, otherwise throws NoSuchElementException .

Usage

From source file:io.gravitee.gateway.env.GatewayConfigurationTest.java

@Test
public void shouldReturnShardingTagsWithPrecedence() {
    System.setProperty(GatewayConfiguration.SHARDING_TAGS_SYSTEM_PROPERTY, "public,private");
    Mockito.when(environment.getProperty(GatewayConfiguration.SHARDING_TAGS_SYSTEM_PROPERTY))
            .thenReturn("intern,extern");
    gatewayConfiguration.afterPropertiesSet();

    Optional<List<String>> shardingTagsOpt = gatewayConfiguration.shardingTags();
    Assert.assertTrue(shardingTagsOpt.isPresent());

    List<String> shardingTags = shardingTagsOpt.get();
    Assert.assertEquals(2, shardingTags.size());
    Assert.assertEquals("public", shardingTags.get(0));
    Assert.assertEquals("private", shardingTags.get(1));
}

From source file:io.gravitee.gateway.services.monitoring.MonitoringService.java

private InstanceEventPayload createInstanceInfo() {
    InstanceEventPayload instanceInfo = new InstanceEventPayload();

    instanceInfo.setId(node.id());// www . j a va  2s .  c  o m
    instanceInfo.setVersion(Version.RUNTIME_VERSION.toString());

    Optional<List<String>> shardingTags = gatewayConfiguration.shardingTags();
    instanceInfo.setTags(shardingTags.isPresent() ? shardingTags.get() : null);

    instanceInfo.setPlugins(plugins());
    instanceInfo.setSystemProperties(new HashMap<>((Map) System.getProperties()));
    instanceInfo.setPort(port);

    Optional<String> tenant = gatewayConfiguration.tenant();
    instanceInfo.setTenant(tenant.isPresent() ? tenant.get() : null);

    try {
        instanceInfo.setHostname(InetAddress.getLocalHost().getHostName());
        instanceInfo.setIp(InetAddress.getLocalHost().getHostAddress());
    } catch (UnknownHostException uhe) {
        LOGGER.warn("Could not get hostname / IP", uhe);
    }

    return instanceInfo;
}

From source file:com.github.horrorho.inflatabledonkey.chunk.engine.standard.StandardChunkEngine.java

@Override
public Map<ChunkServer.ChunkReference, Chunk> fetch(HttpClient httpClient,
        StorageHostChunkListContainer storageHostChunkListContainer,
        Function<ChunkServer.ChunkReference, Optional<byte[]>> getKeyEncryptionKey) {

    ChunkServer.StorageHostChunkList storageHostChunkList = storageHostChunkListContainer
            .storageHostChunkList();// w  ww.j  ava2s .  co  m

    Optional<Map<ChunkServer.ChunkReference, Chunk>> chunkStoreChunks = chunkStoreChunks(
            storageHostChunkListContainer);

    if (chunkStoreChunks.isPresent()) {
        return chunkStoreChunks.get();
    }

    return fetchChunks(httpClient, storageHostChunkListContainer, getKeyEncryptionKey);
}

From source file:com.fitbur.jestify.junit.spring.injector.IndexMockInjector.java

@Override
public void inject() {
    Map<DescriptorKey, ParameterDescriptor> parameterDescriptors = context.getParamaterDescriptors();
    Field field = fieldDescriptor.getField();

    Mock mock = fieldDescriptor.getMock().get();
    Integer index = mock.index();
    Optional<ParameterDescriptor> optional = parameterDescriptors.values().parallelStream()
            .filter(p -> index.equals(p.getIndex())).findFirst();

    ParameterDescriptor parameterDescriptor = optional.get();
    Parameter parameter = parameterDescriptor.getParameter();

    Type fieldType = field.getGenericType();
    Type parameterType = parameter.getParameterizedType();

    checkArgument(fieldType.equals(parameterType),
            "Can not mock field '%s'. Test class field type '%s' and class under test "
                    + "constructor parameter type '%s' at '%d' index do not match.",
            field.getName(), field.getGenericType(), parameterType, index);

    ResolvableType resolver = ResolvableType.forType(parameterType);

    Class rawType;//from  ww w  .  j ava2s .c  om

    if (resolver.hasGenerics()) {
        if (resolver.isAssignableFrom(Provider.class) || resolver.isAssignableFrom(Optional.class)) {
            rawType = resolver.getRawClass();
        } else {
            rawType = resolver.resolve();
        }
    } else {
        rawType = (Class) parameterType;
    }

    checkArgument(arguments[index] == null,
            "Can not mock field '%s'. Multipe test class fields have the same index of '%d'", field.getName(),
            index);

    Object instance = testReifier.reifyField(fieldDescriptor, parameterDescriptor);
    arguments[index] = instance;
}

From source file:org.cyberjos.jcconf2014.node.CloudNodeImpl.java

/**
 * {@inheritDoc}/*from  www  . j a  v  a2 s.co m*/
 */
@Override
public void memberRemoved(final MembershipEvent membershipEvent) {
    final String removedMemberId = membershipEvent.getMember().getUuid();

    logger.info("Found there is one node removed from this cluster: {}", removedMemberId);

    final Optional<NodeRecord> masterNode = this.hazelcastHelper.getMasterNodeRecord();
    if (!masterNode.isPresent() || StringUtils.equals(removedMemberId, masterNode.get().getMemberId())) {
        logger.info("The removed node is a master node. Trying to become the master node.");
        this.hazelcastHelper.setMaster(this);
    } else {
        logger.info("The current master node: {}", masterNode.get());
    }
}

From source file:io.github.jeddict.jpa.spec.sync.AttributeSyncHandler.java

private void syncJavadoc(Optional<Comment> commentOpt, AttributeSnippetLocationType locationType) {
    if (commentOpt.isPresent()) {
        Comment comment = commentOpt.get();
        AttributeSnippet attributeSnippet = new AttributeSnippet();
        attributeSnippet.setLocationType(locationType);
        attributeSnippet/*from ww w  .j ava  2s. c  o m*/
                .setValue(String.format("%" + comment.getBegin().get().column + "s%s", "", comment.toString()));
        if (attribute.getDescription() == null
                || !attributeSnippet.getValue().contains(attribute.getDescription())) {
            attribute.addRuntimeSnippet(attributeSnippet);
        }
    }
}

From source file:com.teradata.logging.TestFrameworkLoggingAppender.java

private Optional<PrintWriter> getFilePrintWriterForCurrentTest() {
    Optional<String> currentTestLogFileName = getCurrentTestLogFileName();
    if (currentTestLogFileName.isPresent()) {
        return Optional.of(getFilePrintWriter(currentTestLogFileName.get()));
    } else {//ww  w.  ja  va 2  s.  com
        return Optional.empty();
    }
}

From source file:io.mapzone.controller.vm.http.ServiceAuthProvision.java

/**
 *
 *//*from   w  ww  .j  a va2s.c o  m*/
protected boolean checkAuthToken() {
    ProjectInstanceIdentifier pid = new ProjectInstanceIdentifier(request.get());

    // check param token; ignore parameter char case
    Optional<String> requestToken = requestParameter(REQUEST_PARAM_TOKEN);
    if (requestToken.isPresent()) {
        if (!isValidToken(requestToken.get(), pid)) {
            throw new HttpProvisionRuntimeException(401, "Given auth token is not valid for this project.");
        }
        return true;
    }

    // check path parts
    String path = StringUtils.defaultString(request.get().getPathInfo());
    for (String part : StringUtils.split(path, '/')) {
        if (isValidToken(part, pid)) {
            return true;
        }
    }
    return false;
}

From source file:it.tidalwave.northernwind.frontend.filesystem.hg.impl.DefaultMercurialRepositoryTest.java

/*******************************************************************************************************************
 *
 ******************************************************************************************************************/
@Test(dependsOnMethods = "must_properly_clone_a_repository", dataProvider = "tagSequenceUpTo0.8")
public void must_properly_update_to_a_tag(final @Nonnull Tag tag) throws Exception {
    // given/*from  ww  w. j  a v  a2 s . c  o m*/
    prepareSourceRepository(Option.UPDATE_TO_PUBLISHED_0_8);
    underTest.clone(sourceRepository.toUri());
    // when
    underTest.updateTo(tag);
    // then
    final Optional<Tag> currentTag = underTest.getCurrentTag();
    assertThat(currentTag.isPresent(), is(true));
    assertThat(currentTag.get(), is(tag));
    // TODO: assert contents
}

From source file:com.opopov.cloud.image.service.ImageStitchingServiceImpl.java

private Optional<DecodedImage> decompressImage(int imageIndex, IndexMap indexMap, ResponseEntity<byte[]> resp) {
    Optional<BufferedImage> image = decompressImage(resp);
    Optional<DecodedImage> result = image.isPresent() ? Optional.of(new DecodedImage(image.get(), imageIndex))
            : Optional.empty();/*from   w  ww  . j a v  a  2  s  . c o m*/
    indexMap.put(imageIndex, result);
    return result;
}