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:spring.travel.site.services.OffersService.java

private String queryString(Optional<Profile> profile, Optional<Loyalty> loyalty) {
    StringBuilder builder = new StringBuilder();

    profile.ifPresent(p -> builder.append("?lifecycle=").append(p.getLifecycle().toString().toLowerCase())
            .append("&spending=").append(p.getSpending().toString().toLowerCase()).append("&gender=")
            .append(p.getGender().toString().toLowerCase()));

    loyalty.ifPresent(l -> builder.append(profile.isPresent() ? "&" : "?").append("loyalty=")
            .append(l.getGroup().toString().toLowerCase()));

    return builder.toString();
}

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

@Transactional
public void readyWorker(Optional<Worker> workerOptional) {
    workerOptional.ifPresent(worker -> {
        worker.setStatus(Worker.Status.READY);
        workerDao.save(worker);/*w  w  w . j  a  v a2  s  . c om*/
    });
}

From source file:io.knotx.repository.impl.FilesystemRepositoryConnectorProxyImpl.java

private MultiMap headers(Optional<String> contentType) {
    MultiMap headers = MultiMap.caseInsensitiveMultiMap();
    contentType.ifPresent(s -> headers.add("Content-Type", s));
    return headers;
}

From source file:org.openmhealth.shim.jawbone.mapper.JawboneBodyEventsDataPointMapper.java

/**
 * Handles some of the basic measure creation activities for body event datapoints and then delegates the creation
 * of the {@link Builder} to subclasses for each individual body event {@link Measure}.
 *
 * @param listEntryNode an individual entry node from the "items" array of a Jawbone endpoint response
 *///ww  w.ja va 2  s . c  om
@Override
protected Optional<T> getMeasure(JsonNode listEntryNode) {

    if (!containsType(listEntryNode, getBodyEventType())) {
        return Optional.empty();
    }

    Optional<Measure.Builder<T, ?>> builderOptional = newMeasureBuilder(listEntryNode);
    if (!builderOptional.isPresent()) {
        return Optional.empty();
    }

    Measure.Builder<T, ?> builder = builderOptional.get();

    setEffectiveTimeFrame(builder, listEntryNode);

    Optional<String> optionalUserNote = asOptionalString(listEntryNode, "note");
    optionalUserNote.ifPresent(builder::setUserNotes);

    return Optional.of(builder.build());
}

From source file:com.tesshu.subsonic.client.sample4_music_andmovie.BinaryDownloadApplication.java

@Bean
protected CommandLineRunner run(RestTemplate restTemplate) throws Exception {
    return args -> {

        File tmpDirectory = new File(tmpPath);
        tmpDirectory.mkdir();/*www . j  a v a 2  s .c o m*/

        Optional<SearchResult2> result2 = search2.getOf("e", null, null, null, null, 1, null, null);
        result2.ifPresent(result -> result.getSongs().forEach(song -> {

            download.download(song, (subject, inputStream) -> {

                File dir = new File(tmpPath + "/" + song.getPath().replaceAll("([^/]+?)?$", StringUtils.EMPTY));
                dir.mkdirs();
                File file = new File(tmpPath + "/" + song.getPath());
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    BufferedInputStream reader = new BufferedInputStream(inputStream);
                    byte buf[] = new byte[256];
                    int len;
                    while ((len = reader.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                    fos.close();
                    reader.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                LOG.info(file.getAbsolutePath());
            }, callback);
        }));

        tmpDirectory.deleteOnExit();
    };

}

From source file:spring.travel.site.services.AdvertService.java

private String url(int count, Optional<Profile> profile) {
    StringBuilder builder = new StringBuilder(advertServiceUrl).append("?count=").append(count);
    profile.ifPresent(p -> builder.append("&target=").append(target(p)));
    return builder.toString();
}

From source file:fi.helsinki.opintoni.service.CourseService.java

public Set<CourseDto> getCourses(Optional<String> studentNumber, Optional<String> teacherNumber,
        Locale locale) {/*w  ww  . j  a  v a2 s.c o  m*/
    Set<CourseDto> courseDtos = new HashSet<>();

    teacherNumber.ifPresent(number -> courseDtos.addAll(getTeacherCourses(number, locale)));

    studentNumber.ifPresent(number -> courseDtos.addAll(getStudentCourses(number, locale)));

    return courseDtos;
}

From source file:com.ikanow.aleph2.analytics.spark.utils.SparkTechnologyUtils.java

/** Builds objects for all the aleph2 inputs and provides a method to use them in context-dependent ways 
 * @param context//from w w  w  .j a  v  a2s. com
 * @param bucket
 * @param job
 * @param config
 * @param per_input_action - user lambda that determines how they are used
 */
public static final void buildAleph2Inputs(final IAnalyticsContext context, final DataBucketBean bucket,
        final AnalyticThreadJobBean job, final Optional<ProcessingTestSpecBean> maybe_test_spec,
        final Configuration config, final Set<String> exclude_names,
        BiConsumer<AnalyticThreadJobInputBean, Job> per_input_action) {
    transformInputBean(Optionals.ofNullable(job.inputs()).stream(), maybe_test_spec)
            .filter(input -> !exclude_names.contains(input.name()))
            .forEach(Lambdas.wrap_consumer_u(input_with_test_settings -> {

                final Optional<IBucketLogger> a2_logger = Optional
                        .ofNullable(context.getLogger(Optional.of(bucket)));

                final List<String> paths = context.getInputPaths(Optional.empty(), job,
                        input_with_test_settings);

                if (!paths.isEmpty()) {

                    _logger.info(ErrorUtils.get("Adding storage paths for bucket {0}: {1}", bucket.full_name(),
                            paths.stream().collect(Collectors.joining(";"))));

                    a2_logger.ifPresent(l -> l.log(Level.INFO, true,
                            () -> ErrorUtils.get("Adding storage paths for bucket {0}: {1}", bucket.full_name(),
                                    paths.stream().collect(Collectors.joining(";"))),
                            () -> SparkTechnologyService.class.getSimpleName() + "."
                                    + Optional.ofNullable(job.name()).orElse("no_name"),
                            () -> "startAnalyticJobOrTest"));

                    //DEBUG
                    //System.out.println(ErrorUtils.get("Adding storage paths for bucket {0}: {1}", bucket.full_name(), paths.stream().collect(Collectors.joining(";"))));   

                    final Job input_job = Job.getInstance(config);
                    input_job.setInputFormatClass(BeFileInputFormat_Pure.class);
                    paths.stream().forEach(Lambdas
                            .wrap_consumer_u(path -> FileInputFormat.addInputPath(input_job, new Path(path))));
                    // (Add the input config in)
                    input_job.getConfiguration().set(HadoopBatchEnrichmentUtils.BE_BUCKET_INPUT_CONFIG,
                            BeanTemplateUtils.toJson(input_with_test_settings).toString());
                    per_input_action.accept(input_with_test_settings, input_job);
                } else { // not easily available in HDFS directory format, try getting from the context

                    Optional<HadoopBatchEnrichmentUtils.HadoopAccessContext> input_format_info = context
                            .getServiceInput(HadoopBatchEnrichmentUtils.HadoopAccessContext.class,
                                    Optional.empty(), job, input_with_test_settings);
                    if (!input_format_info.isPresent()) {
                        _logger.warn(ErrorUtils.get("Tried but failed to get input format from {0}",
                                BeanTemplateUtils.toJson(input_with_test_settings)));

                        a2_logger.ifPresent(l -> l.log(Level.WARN, true,
                                () -> ErrorUtils.get("Tried but failed to get input format from {0}",
                                        BeanTemplateUtils.toJson(input_with_test_settings)),
                                () -> SparkTechnologyService.class.getSimpleName() + "."
                                        + Optional.ofNullable(job.name()).orElse("no_name"),
                                () -> "startAnalyticJobOrTest"));

                        //DEBUG
                        //System.out.println(ErrorUtils.get("Tried but failed to get input format from {0}", BeanTemplateUtils.toJson(input_with_test_settings)));
                    } else {
                        _logger.info(ErrorUtils.get("Adding data service path for bucket {0}: {1}",
                                bucket.full_name(), input_format_info.get().describe()));

                        a2_logger.ifPresent(l -> l.log(Level.INFO, true,
                                () -> ErrorUtils.get("Adding data service path for bucket {0}: {1}",
                                        bucket.full_name(), input_format_info.get().describe()),
                                () -> SparkTechnologyService.class.getSimpleName() + "."
                                        + Optional.ofNullable(job.name()).orElse("no_name"),
                                () -> "startAnalyticJobOrTest"));

                        //DEBUG
                        //System.out.println(ErrorUtils.get("Adding data service path for bucket {0}: {1}", bucket.full_name(),input_format_info.get().describe()));

                        final Job input_job = Job.getInstance(config);
                        input_job.setInputFormatClass(
                                input_format_info.get().getAccessService().either(l -> l.getClass(), r -> r));
                        input_format_info.get().getAccessConfig().ifPresent(map -> {
                            map.entrySet().forEach(kv -> input_job.getConfiguration().set(kv.getKey(),
                                    kv.getValue().toString()));
                        });
                        per_input_action.accept(input_with_test_settings, input_job);
                    }
                }
            }));
}

From source file:com.teradata.benchto.driver.BenchmarkProperties.java

private void addForToStringOptionalField(ToStringHelper toStringHelper, String fieldName,
        Optional optionalField) {
    optionalField.ifPresent(value -> toStringHelper.add(fieldName, value));
}

From source file:com.tesshu.subsonic.client.sample2_service_customize.ReverseOrderOfArtistsApplication.java

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

    return args -> {

        // see ServiceCustomizer
        Optional<MusicFolder> musicFolder = getMusicFolders.getList().stream()
                .filter(folder -> "Music".equals(folder.getName())).findFirst();

        musicFolder.ifPresent(folder -> {
            Optional<Indexes> indexes = getIndexes.getOf(folder, null);
            indexes.ifPresent(i -> i.getIndexes().stream().flatMap(index -> index.getArtists().stream())
                    .sorted(comparing(Artist::getName).reversed()).forEach(artist -> LOG.info(artist)));
        });/*from  ww  w .j a v a2  s  .c  o m*/

    };
}