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:ee.ria.xroad.opmonitordaemon.HealthDataRequestHandler.java

private LastPeriodStatisticsType buildLastPeriodStats(ServiceId service) {
    LastPeriodStatisticsType lastPeriodStats = OBJECT_FACTORY.createLastPeriodStatisticsType();

    lastPeriodStats.setSuccessfulRequestCount(0);
    Optional<Counter> successfulEventCount = Optional
            .ofNullable(findCounter(healthMetricRegistry, getRequestCounterName(service, true)));
    successfulEventCount.ifPresent(c -> lastPeriodStats.setSuccessfulRequestCount((int) c.getCount()));

    lastPeriodStats.setUnsuccessfulRequestCount(0);
    Optional<Counter> unsuccessfulEventCount = Optional
            .ofNullable(findCounter(healthMetricRegistry, getRequestCounterName(service, false)));
    unsuccessfulEventCount.ifPresent(c -> lastPeriodStats.setUnsuccessfulRequestCount((int) c.getCount()));

    if (lastPeriodStats.getSuccessfulRequestCount() > 0) {
        Optional<Histogram> requestDuration = Optional
                .ofNullable(findHistogram(healthMetricRegistry, getRequestDurationName(service)));
        requestDuration.ifPresent(h -> {
            lastPeriodStats.setRequestMinDuration(h.getSnapshot().getMin());
            lastPeriodStats.setRequestAverageDuration(h.getSnapshot().getMean());
            lastPeriodStats.setRequestMaxDuration(h.getSnapshot().getMax());
            lastPeriodStats.setRequestDurationStdDev(h.getSnapshot().getStdDev());
        });//from ww w  . jav  a 2  s . co m

        Optional<Histogram> requestSoapSize = Optional
                .ofNullable(findHistogram(healthMetricRegistry, getRequestSoapSizeName(service)));
        requestSoapSize.ifPresent(h -> {
            lastPeriodStats.setRequestMinSoapSize(h.getSnapshot().getMin());
            lastPeriodStats.setRequestAverageSoapSize(h.getSnapshot().getMean());
            lastPeriodStats.setRequestMaxSoapSize(h.getSnapshot().getMax());
            lastPeriodStats.setRequestSoapSizeStdDev(h.getSnapshot().getStdDev());
        });

        Optional<Histogram> responseSoapSize = Optional
                .ofNullable(findHistogram(healthMetricRegistry, getResponseSoapSizeName(service)));
        responseSoapSize.ifPresent(h -> {
            lastPeriodStats.setResponseMinSoapSize(h.getSnapshot().getMin());
            lastPeriodStats.setResponseAverageSoapSize(h.getSnapshot().getMean());
            lastPeriodStats.setResponseMaxSoapSize(h.getSnapshot().getMax());
            lastPeriodStats.setResponseSoapSizeStdDev(h.getSnapshot().getStdDev());
        });
    }

    return lastPeriodStats;
}

From source file:com.github.mrenou.jacksonatic.internal.introspection.AnnotatedClassConstructor.java

@SafeVarargs
private final ClassMappingInternal<Object> mergeAndPutInMergedClassesMapping(
        ClassesMapping mergedClassesMapping, Class<Object> superType,
        Optional<ClassMappingInternal<Object>>... classMappings) {
    Optional<ClassMappingInternal<Object>> classMappingOpt = Mergeable.merge(classMappings)
            .map(classMapping -> classMapping.getType() != superType
                    ? new ClassMappingInternal<>(superType).mergeWith(classMapping)
                    : classMapping);// w  w w .  j ava 2s. com
    classMappingOpt.ifPresent(classMapping -> mergedClassesMapping.put(superType, classMapping));
    return classMappingOpt.orElse(null);
}

From source file:nu.yona.server.ThymeleafConfigurationTest.java

private String buildSms(Optional<Locale> locale, String requestingUserFirstName, String emailAddress) {
    Context ctx = ThymeleafUtil.createContext();
    ctx.setVariable("requestingUserFirstName", requestingUserFirstName);
    ctx.setVariable("emailAddress", emailAddress);
    locale.ifPresent(l -> ctx.setLocale(l));

    return smsTemplateEngine.process("buddy-invitation.txt", ctx);
}

From source file:com.epam.ta.reportportal.core.project.impl.GetProjectStatisticHandler.java

@Override
public Iterable<ProjectInfoResource> getAllProjectsInfo(Filter filter, Pageable pageable) {
    final Page<ProjectInfoResource> preAssembled = projectInfoResourceAssembler
            .toPagedResources(projectRepository.findByFilter(filter, pageable));
    for (ProjectInfoResource project : preAssembled) {
        final Optional<Launch> lastLaunch = launchRepository.findLastLaunch(project.getProjectId(),
                DEFAULT.name());//  w  w  w. j av a2 s. c o  m
        lastLaunch.ifPresent(launch -> project.setLastRun(launch.getStartTime()));
        project.setLaunchesQuantity(
                launchRepository.findLaunchesQuantity(project.getProjectId(), DEFAULT.name(), null));
    }
    return preAssembled;
}

From source file:de.speexx.jira.jan.command.transition.IssueTransitionFetcher.java

@Override
public void execute() {

    int count = 0;
    int startIndex = 0;
    int total = -1;

    final List<IssueInfo> issueInfos = new ArrayList<>();

    final AtomicBoolean header = new AtomicBoolean(false);
    try (final JiraRestClient restClient = this.execCtx.newJiraClient()) {
        do {/*ww w. ja va  2s .  c o m*/
            final String q = getQuery()
                    .orElseThrow(() -> new JiraAnalyzeException("No query given for fetching transitions"));
            final SearchResult searchResult = fetchIssues(restClient, q, startIndex);
            total = total == -1 ? searchResult.getTotal() : total;
            startIndex += getFetchLimit();

            for (final Issue searchResultIssue : searchResult.getIssues()) {
                count++;
                final Issue issue = fetchIssueForSearchResult(restClient, searchResultIssue);
                final Iterable<ChangelogGroup> changeLogs = issue.getChangelog();

                final Optional<IssueInfo> issueInfo = handleChangeLog(changeLogs, issue);
                issueInfo.ifPresent(info -> {
                    info.issueType = fetchIssueType(issue);
                    info.key = issue.getKey();
                    info.resolution = fetchResolution(issue);
                    info.priority = fetchPriority(issue);
                    info.created = fetchCreationDateTime(issue);
                    issueInfos.add(info);
                    this.execCtx.log("ISSUE INFO: {}", info);
                });
            }
            this.execCtx.log("total: {} - count: {}", total, count);
        } while (total != count);
    } catch (final IOException e) {
        throw new JiraAnalyzeException(e);
    }
    exportAsCsv(issueInfos, header);
}

From source file:org.jboss.pnc.buildagent.server.termserver.Term.java

public Term(String context, Runnable onDestroy, ScheduledExecutorService executor,
        Optional<ReadOnlyChannel> appendReadOnlyChannel) {
    this.context = context;
    this.onDestroy = onDestroy;
    this.appendReadOnlyChannel = appendReadOnlyChannel;

    webSocketTtyConnection = new WebSocketTtyConnection(executor);
    appendReadOnlyChannel.ifPresent(ch -> webSocketTtyConnection.addReadonlyChannel(ch));
    log.debug("Creating new TtyBridge.");
}

From source file:io.syndesis.controllers.integration.IntegrationController.java

private void checkIntegrationStatus(Integration integration) {
    if (integration == null) {
        return;/*from   w  ww .  j ava 2  s.c om*/
    }
    Optional<Integration.Status> desired = integration.getDesiredStatus();
    Optional<Integration.Status> current = integration.getCurrentStatus();
    if (!current.equals(desired)) {
        desired.ifPresent(desiredStatus -> integration.getId().ifPresent(integrationId -> {
            StatusChangeHandlerProvider.StatusChangeHandler statusChangeHandler = handlers.get(desiredStatus);
            if (statusChangeHandler != null) {
                LOG.info(
                        "Integration {} : Desired status \"{}\" != current status \"{}\" --> calling status change handler",
                        integrationId, desiredStatus.toString(), current.map(Enum::toString).orElse("[none]"));
                callStatusChangeHandler(statusChangeHandler, integrationId);
            }
        }));
    } else {
        // When the desired state is reached remove the marker so that a next change trigger a check again
        // Doesn't harm when no such key exists
        desired.ifPresent(d -> scheduledChecks.remove(getIntegrationMarkerKey(integration)));
    }
}

From source file:alfio.controller.TicketController.java

@RequestMapping(value = "/event/{eventName}/cancel-ticket", method = RequestMethod.POST)
public String cancelTicket(@PathVariable("eventName") String eventName,
        @RequestParam("ticketId") String ticketIdentifier) {
    Optional<Triple<Event, TicketReservation, Ticket>> oData = ticketReservationManager
            .fetchCompleteAndAssigned(eventName, ticketIdentifier);
    oData.ifPresent(triple -> ticketReservationManager.releaseTicket(triple.getLeft(), triple.getMiddle(),
            triple.getRight()));// w  ww. j  av a2s.c om
    return "redirect:/event/" + eventName;
}

From source file:enmasse.controller.api.v3.amqp.AmqpFlavorsApiTest.java

private Message doRequest(String method, Object body, Optional<String> addressProperty) throws IOException {
    Message message = Message.Factory.create();
    message.setAddress("$flavor");
    message.setContentType("application/json");
    message.setBody(new AmqpValue(mapper.writeValueAsString(body)));
    Map<String, String> properties = new LinkedHashMap<>();
    properties.put("method", method);
    addressProperty.ifPresent(address -> properties.put("flavor", address));
    message.setApplicationProperties(new ApplicationProperties(properties));

    return flavorsService.handleMessage(message);
}

From source file:ch.wisv.areafiftylan.seats.service.SeatServiceImpl.java

@Override
public boolean reserveSeatForTicket(String groupname, int seatnumber, Long ticketId) {
    Ticket ticket = ticketRepository.findOne(ticketId);

    if (!ticket.isValid()) {
        throw new InvalidTicketException("Unable to reserve seat for an invalid Ticket");
    }/*ww  w . j ava  2  s. com*/

    Optional<Seat> previousSeat = seatRepository.findByTicketId(ticketId);

    // We can only reserve one seat at a time, to prevent the extremely unlikely event of simultaneous requests
    synchronized (seatReservationLock) {
        Seat seat = seatRepository.findBySeatGroupAndSeatNumber(groupname, seatnumber);
        previousSeat.ifPresent(s -> s.setTicket(null));
        if (!seat.isTaken()) {
            seat.setTicket(ticket);
            seatRepository.saveAndFlush(seat);
            return true;
        } else {
            return false;
        }
    }
}