Example usage for java.util Optional ifPresent

List of usage examples for java.util Optional ifPresent

Introduction

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

Prototype

public void ifPresent(Consumer<? super T> action) 

Source Link

Document

If a value is present, performs the given action with the value, otherwise does nothing.

Usage

From source file:io.github.carlomicieli.footballdb.starter.Samples.java

@Override
public void run(String... args) throws Exception {
    Optional<TeamRoster> roster = teamRosters.parse("/teams/sanfrancisco49ers/roster?team=SF");

    roster.ifPresent(r -> r.playersStream().forEach(p -> App.log().info("> {}", p)));

    Optional<PlayerProfile> peytonManningProfile = playerProfile.parse("/player/peytonmanning/2501863/profile");
    peytonManningProfile.ifPresent(p -> App.log().info("{}", p));

    Optional<PlayerCareer> drewBreesCareer = playerCareer.parse("/player/drewbrees/2504775/profile");
    drewBreesCareer.ifPresent(cr -> cr.seasonStream().forEach(s -> App.log().info("> {}", s)));
}

From source file:nu.yona.server.rest.RestClientErrorHandler.java

@Override
public void handleError(ClientHttpResponse response) throws IOException {
    logger.error("Response error: {} {}", getStatusCode(response), response.getStatusText());
    Optional<ErrorResponseDto> yonaErrorResponse = getYonaErrorResponse(response);
    yonaErrorResponse.ifPresent(yer -> {
        throw UpstreamException.yonaException(getStatusCode(response), yer.getCode(), yer.getMessage());
    });//from w  ww  .  ja v a 2  s .c om
    throw UpstreamException.remoteServiceError(getStatusCode(response),
            convertStreamToString(response.getBody()));
}

From source file:pzalejko.iot.hardware.home.core.task.TemperatureTask.java

@Override
public void run() {
    final Optional<TemperatureEntity> temperatureEntity = service.getTemperatureEntity();
    temperatureEntity.ifPresent(t -> eventBus.postLocal(t, EventType.TEMPERATURE_VALUE));
}

From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java

/** (1/3) Calls user code to extract vertices and edges
 * @param batch// www.  j  a  va 2s  . c o m
 * @param batch_size
 * @param grouping_key
 * @param maybe_decomposer
 * @return
 */
public static List<ObjectNode> buildGraph_getUserGeneratedAssets(final Stream<Tuple2<Long, IBatchRecord>> batch,
        final Optional<Integer> batch_size, final Optional<JsonNode> grouping_key,
        final Optional<Tuple2<IEnrichmentBatchModule, GraphDecompEnrichmentContext>> maybe_decomposer) {
    // First off build the edges and vertices

    maybe_decomposer.ifPresent(handler -> handler._1().onObjectBatch(batch, batch_size, grouping_key));

    final List<ObjectNode> vertices_and_edges = maybe_decomposer
            .map(context -> context._2().getAndResetVertexList()).orElse(Collections.emptyList());

    return vertices_and_edges;
}

From source file:com.tesshu.subsonic.client.sample3_create_url.CreateUrlApplication.java

@Bean
protected CommandLineRunner run(RestTemplate restTemplate) throws Exception {

    return args -> {

        final IRequestUriObserver uriCallBack = (subject, uri) -> {
            movieUrl = uri.toString();//from  w  w  w.  j  a  v  a2 s.c o  m
        };

        final String format = "mp4";

        Optional<SearchResult2> result2 = search2.getOf("CORPSE BRIDE", 0, null, 0, null, 10, null, null);

        result2.ifPresent(r -> {
            Optional<Child> movie = r.getSongs().stream().filter(child -> MediaType.VIDEO == child.getType())
                    .filter(child -> format.equals(child.getSuffix())).findFirst();
            movie.ifPresent(m -> {
                stream.stream(m, null, format, null, null, true, false, null, uriCallBack);
            });

            LOG.info(movieUrl);

        });
    };
}

From source file:com.rockagen.gnext.test.BaseTest.java

public void refresh() {
    Optional<Account> acc = accountServ.loadByUid(uid);
    acc.ifPresent(x -> {
        account = x;/* w  w  w  .j  av  a 2 s.  c  o  m*/
        accountId = account.getId();
    });

    authUserServ.load(uid).ifPresent(x -> user = x);
}

From source file:com.largecode.interview.rustem.service.UsersServiceImpl.java

@Override
public void deleteUser(Long id) {
    LOGGER.debug("Delete user by id ={}", id);
    Optional<User> userInDb = Optional.ofNullable(userRepository.findOne(id));
    userInDb.ifPresent((user) -> {
        userRepository.delete(user);//from   w w w.  j a  v a 2s  .c  om
    });
    userInDb.orElseThrow(
            () -> new NoSuchElementException(String.format("User=%s not found for deleting.", id)));

}

From source file:pzalejko.iot.hardware.home.core.service.sender.InternalMqttRemoteCallback.java

@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
    LOG.debug(LogMessages.RECEIVED_MESSAGE, topic, message);

    final Optional<EventType> eventType = Optional.ofNullable(eventTopicMapper.getEventType(topic));
    eventType.ifPresent(t -> {
        final Serializable data = eventConverter.convertIn(t, message.getPayload());
        eventBus.postRemote(data, t);//from w  ww.j  ava2 s.  c  o m
    });
}

From source file:com.largecode.interview.rustem.service.UsersServiceImpl.java

@Override
public void updateUser(Long id, UserDto userDto, Role roleOfCreator) {
    LOGGER.debug("Update user id = {} with data {}", id, userDto);
    Optional<User> userInDb = Optional.ofNullable(userRepository.findOne(id));
    userInDb.ifPresent((user) -> {
        roleOfCreator.modifyUserProperties(userDto, user);
        userRepository.saveAndFlush(user);
    });//from ww  w.j a  va  2  s. co m
    userInDb.orElseThrow(
            () -> new NoSuchElementException(String.format("User=%s not found for updating.", id)));

}

From source file:com.github.tddts.jet.service.impl.LoginServiceImpl.java

@Override
public void processLogin(Supplier<Optional<Pair<String, String>>> credentialsSupplier,
        Consumer<URI> loginUriConsumer) {
    AuthorizationType authType = userBean.getAuthorizationType();

    server.start();//  ww  w . ja  v a2  s .  c  om

    if (authType.isImplicit()) {
        loginUriConsumer.accept(authService.getLoginPageURI());
    }

    if (authType.isDev()) {
        Optional<Pair<String, String>> credentialsPair = credentialsSupplier.get();

        credentialsPair.ifPresent(creds -> {
            userBean.setClientId(creds.getKey());
            userBean.setSercretKey(creds.getValue());
            loginUriConsumer.accept(authService.getLoginPageURI(userBean.getClientId()));
        });

    }
}