Example usage for java.util Optional map

List of usage examples for java.util Optional map

Introduction

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

Prototype

public <U> Optional<U> map(Function<? super T, ? extends U> mapper) 

Source Link

Document

If a value is present, returns an Optional describing (as if by #ofNullable ) the result of applying the given mapping function to the value, otherwise returns an empty Optional .

Usage

From source file:com.ethercamp.harmony.service.PeersService.java

private PeerDTO createPeerDTO(String peerId, String ip, long lastPing, double avgLatency, int reputation,
        boolean isActive, NodeStatistics nodeStatistics, long maxBlockNumber) {
    // code or ""

    final Optional<Country> country = lookupService.map(service -> service.getCountry(ip));
    final String country2Code = country.map(c -> c.getCode()).orElse("");

    // code or ""
    final String country3Code = iso2CountryCodeToIso3CountryCode(country2Code);

    return new PeerDTO(peerId, ip, country3Code, country2Code, lastPing, avgLatency, reputation, isActive,
            getPeerDetails(nodeStatistics, country.map(Country::getName).orElse("Unknown location"),
                    maxBlockNumber));//from  w w  w.ja  v  a  2  s  . c  o  m
}

From source file:natalia.dymnikova.cluster.scheduler.impl.SetFlowFactory.java

private Stage makeStages(final List<StageContainer> resolvedStages, final List<Optional<Address>> addresses,
        final int i) {
    final StageContainer stageContainer = resolvedStages.get(i);
    final Optional<Address> currAddress = addresses.get(i);
    final List<Stage> children = stageContainer.previous.stream()
            .map(stage -> makeStages(resolvedStages, addresses, stage.id)).collect(toList());
    return currAddress.map(address -> {
        if (stageContainer.stageType == Merge) {
            return flowMerger.createMergeStages(children, stageContainer,
                    previousStageContainerAddress(resolvedStages, stageContainer, addresses));
        }/*  ww w.  ja  va2  s  .c  o  m*/

        return Stage.newBuilder().setOperator(stageContainer.remoteBytes)
                .setAddress(currAddress.get().toString()).setType(stageContainer.stageType)
                .setId(stageContainer.id).addAllStages(children).build();

    }).orElseThrow(() -> new NoSuchElementException("No candidate for stage " + stageContainer.action));
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.core.CoarseGrainedOptimizer.java

private List<Triple<Integer, Optional<Double>, Boolean>> alterUntilBreakPoint(SolutionPerJob solPerJob,
        Function<Integer, Integer> updateFunction, Function<Double, Double> fromResult,
        Predicate<Double> feasibilityCheck, Predicate<Double> stoppingCondition,
        BiPredicate<Double, Double> incrementCheck, Predicate<Integer> vmCheck) {
    List<Triple<Integer, Optional<Double>, Boolean>> lst = new ArrayList<>();
    Optional<Double> previous = Optional.empty();
    boolean shouldKeepGoing = true;

    while (shouldKeepGoing) {
        Pair<Optional<Double>, Long> simulatorResult = dataProcessor.simulateClass(solPerJob);
        Optional<Double> maybeResult = simulatorResult.getLeft();
        Optional<Double> interestingMetric = maybeResult.map(fromResult);

        Integer nVM = solPerJob.getNumberVM();
        lst.add(new ImmutableTriple<>(nVM, maybeResult,
                interestingMetric.filter(feasibilityCheck).isPresent()));
        boolean terminationCriterion = !checkState();
        logger.trace("terminationCriterion is " + terminationCriterion + " after checkState()");
        terminationCriterion |= vmCheck.test(nVM);
        logger.trace("terminationCriterion is " + terminationCriterion + " after vmCheck.test()");
        terminationCriterion |= interestingMetric.filter(stoppingCondition).isPresent();
        logger.trace("terminationCriterion is " + terminationCriterion + " after filter");
        if (previous.isPresent() && interestingMetric.isPresent()
                && (dataService.getScenario().getTechnology() != Technology.STORM
                        || interestingMetric.get() == 0.0)) {
            terminationCriterion |= incrementCheck.test(previous.get(), interestingMetric.get());
        }/*from   w  ww.  j av a2s.  c o  m*/
        shouldKeepGoing = !terminationCriterion;
        previous = interestingMetric;
        if (dataService.getScenario().getTechnology() == Technology.STORM) {
            logger.trace(interestingMetric.orElse(Double.NaN) + " vs. " + solPerJob.getJob().getU());
        } else {
            logger.trace(interestingMetric.orElse(Double.NaN) + " vs. " + solPerJob.getJob().getD());
        }
        if (shouldKeepGoing) {
            String message = String.format("class %s -> num VM: %d, simulator result: %f, metric: %f",
                    solPerJob.getId(), nVM, maybeResult.orElse(Double.NaN),
                    interestingMetric.orElse(Double.NaN));
            logger.info(message);
            solPerJob.updateNumberVM(updateFunction.apply(nVM));
        }
    }

    return lst;
}

From source file:me.yanaga.winter.data.jpa.PersonRepositoryTest.java

@Test
public void testSaveSupplierAndFindOne() {
    Person.Supplier supplier = Person.supplier("Yanaga");
    Person saved = personRepository.save(supplier);
    assertNotNull(saved.getId());/*from  w  w w . j a  v a  2 s .c o m*/
    Optional<Person> found = personRepository.findOne(saved.getId());
    assertNotNull(found);
    assertThat(saved.getId()).isEqualTo(found.map(Person::getId).get());
}

From source file:me.yanaga.winter.data.jpa.PersonRepositoryTest.java

@Test
public void testSaveEntityBuilderAndFindOne() {
    Person.Builder builder = Person.builder("Yanaga");
    Person saved = personRepository.save(builder);
    assertNotNull(saved.getId());// w w  w.j  a  v  a  2 s. co  m
    Optional<Person> found = personRepository.findOne(saved.getId());
    assertNotNull(found);
    assertThat(saved.getId()).isEqualTo(found.map(Person::getId).get());
}

From source file:me.yanaga.winter.data.jpa.PersonRepositoryTest.java

@Test
public void testSaveAndFindOne() {
    Person person = new Person();
    person.setName("Yanaga");
    Person saved = personRepository.save(person);
    assertNotNull(saved.getId());/*from  w ww.  j ava 2s  . co m*/
    Optional<Person> found = personRepository.findOne(saved.getId());
    assertNotNull(found);
    assertThat(saved.getId()).isEqualTo(found.map(Person::getId).get());
}

From source file:org.ow2.proactive.connector.iaas.service.InstanceService.java

public Set<Instance> createInstance(String infrastructureId, Instance instance) {

    Optional<Infrastructure> optionalInfrastructure = Optional
            .ofNullable(infrastructureService.getInfrastructure(infrastructureId));

    Set<Instance> instancesCreated = optionalInfrastructure
            .map(infrastructure -> cloudManager.createInstance(infrastructure, instance))
            .orElseThrow(() -> new NotFoundException(
                    "infrastructure id : " + infrastructureId + " does not exists"));

    optionalInfrastructure.ifPresent(/*  w  ww.  j  av  a2  s  . co  m*/
            infrastructure -> instanceCache.registerInfrastructureInstances(infrastructure, instancesCreated));

    return instancesCreated;
}

From source file:org.ambraproject.wombat.service.remote.UserApiImpl.java

/**
 * This method fetches the NED user credentials.
 *
 * <ul>//from ww  w .j  a v  a2s.  co m
 *  <li>NED Server URL</li>
 *  <li>User name</li>
 *  <li>Password</li>
 * </ul>
 *
 * @return The {@link UserApiConfiguration}
 */
private UserApiConfiguration fetchApiConfiguration() {
    final Optional<RuntimeConfiguration.UserApiConfiguration> userApiConfig = runtimeConfiguration
            .getUserApiConfiguration();
    final ImmutableMap<String, String> userConfigData = userApiConfig
            .map(config -> ImmutableMap.of("server", config.getServerUrl(), "authorizationAppName",
                    config.getAppName(), "authorizationPassword", config.getPassword()))
            .orElseThrow(() -> new RuntimeException("userApi is not configured"));

    final String server = userConfigData.get("server");
    if (server == null) {
        throw new RuntimeException("userApi is not configured");
    }

    return new UserApiConfiguration(server, userConfigData.get("authorizationAppName"),
            userConfigData.get("authorizationPassword"));
}

From source file:org.apache.james.jmap.methods.integration.cucumber.GetMessagesMethodStepdefs.java

private String serialize(Optional<Map<String, String>> headers) {
    return headers.map(map -> map.entrySet()).map(entriesToString()).orElse("");
}

From source file:com.dickthedeployer.dick.web.service.JobBuildService.java

@Transactional
public Optional<BuildOrder> peekBuildFor(String workerName) {
    workerService.onHeartbeat(workerName);
    Worker worker = workerDao.findByName(workerName).get();
    Optional<JobBuild> jobBuildOptional = jobBuildDao.findByStatusAndWorker(JobBuild.Status.READY, worker);

    return jobBuildOptional.map(jobBuild -> prepareBuildOrder(jobBuild, worker));
}