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:alfio.manager.CheckInManager.java

public Optional<String> confirmOnSitePayment(String ticketIdentifier) {
    Optional<String> uuid = findAndLockTicket(ticketIdentifier)
            .filter(t -> t.getStatus() == TicketStatus.TO_BE_PAID).map(Ticket::getUuid);

    uuid.ifPresent(this::acquire);
    return uuid;/*from w ww.j a v a 2  s .  co m*/
}

From source file:com.bouncestorage.swiftproxy.v1.AccountResource.java

@GET
public Response getAccount(@NotNull @PathParam("account") String account,
        @QueryParam("limit") Optional<Integer> limit, @QueryParam("marker") Optional<String> marker,
        @QueryParam("end_marker") Optional<String> endMarker, @QueryParam("format") Optional<String> format,
        @QueryParam("prefix") Optional<String> prefix, @QueryParam("delimiter") Optional<String> delimiter,
        @HeaderParam("X-Auth-Token") String authToken,
        @HeaderParam("X-Newest") @DefaultValue("false") boolean newest,
        @HeaderParam("Accept") Optional<String> accept) {
    delimiter.ifPresent(x -> logger.info("delimiter not supported yet"));

    BlobStore blobStore = getBlobStore(authToken).get();
    ArrayList<ContainerEntry> entries = blobStore.list().stream().map(StorageMetadata::getName)
            .filter(name -> marker.map(m -> name.compareTo(m) > 0).orElse(true))
            .filter(name -> endMarker.map(m -> name.compareTo(m) < 0).orElse(true))
            .filter(name -> prefix.map(name::startsWith).orElse(true)).map(ContainerEntry::new)
            .collect(Collectors.toCollection(ArrayList::new));

    MediaType formatType;//from  w  w  w.  j  av  a  2s  .  c  om
    if (format.isPresent()) {
        formatType = BounceResourceConfig.getMediaType(format.get());
    } else if (accept.isPresent()) {
        formatType = MediaType.valueOf(accept.get());
    } else {
        formatType = MediaType.TEXT_PLAIN_TYPE;
    }

    if (blobStore.getContext().unwrap().getId().equals("transient")) {
        entries.sort((a, b) -> a.getName().compareTo(b.getName()));
    }

    long count = entries.size();
    limit.ifPresent((max) -> {
        if (entries.size() > max) {
            entries.subList(max, entries.size()).clear();
        }
    });

    Account root = new Account();
    root.name = account;
    root.container = entries;
    return output(root, entries, formatType).header("X-Account-Container-Count", count)
            .header("X-Account-Object-Count", -1).header("X-Account-Bytes-Used", -1).header("X-Timestamp", -1)
            .header("X-Trans-Id", -1).header("Accept-Ranges", "bytes").build();
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Utility function to create a mapping out of all the different system components (see also ElasticsearchUtils)
 * @param bucket/*from   w  ww .ja va2s .  c o  m*/
 * @param config
 * @return
 */
public static XContentBuilder createIndexMapping(final DataBucketBean bucket,
        final Optional<String> secondary_buffer, final boolean is_primary,
        final ElasticsearchIndexServiceConfigBean schema_config, final ObjectMapper mapper,
        final String index_type) {
    final JsonNode default_mapping = mapper.convertValue(schema_config.search_technology_override(),
            JsonNode.class);

    // Also get JsonNodes for the default field config bit

    final boolean columnar_enabled = Optional.ofNullable(bucket.data_schema())
            .map(DataSchemaBean::columnar_schema).filter(s -> Optional.ofNullable(s.enabled()).orElse(true))
            .isPresent();

    final boolean doc_enabled = Optional.ofNullable(bucket.data_schema()).map(DataSchemaBean::document_schema)
            .filter(s -> Optional.ofNullable(s.enabled()).orElse(true)).isPresent();

    // (these can't be null by construction)
    final JsonNode enabled_analyzed_field = columnar_enabled
            ? mapper.convertValue(schema_config.columnar_technology_override().enabled_field_data_analyzed(),
                    JsonNode.class)
            : mapper.createObjectNode();
    final JsonNode enabled_not_analyzed_field = columnar_enabled
            ? mapper.convertValue(schema_config.columnar_technology_override().enabled_field_data_notanalyzed(),
                    JsonNode.class)
            : mapper.createObjectNode();
    final JsonNode default_analyzed_field = columnar_enabled
            ? mapper.convertValue(schema_config.columnar_technology_override().default_field_data_analyzed(),
                    JsonNode.class)
            : mapper.createObjectNode();
    final JsonNode default_not_analyzed_field = columnar_enabled
            ? mapper.convertValue(schema_config.columnar_technology_override().default_field_data_notanalyzed(),
                    JsonNode.class)
            : mapper.createObjectNode();
    final Optional<JsonNode> doc_schema = doc_enabled
            ? Optional.ofNullable(mapper.convertValue(schema_config.document_schema_override(), JsonNode.class))
            : Optional.empty();

    // Get a list of field overrides Either<String,Tuple2<String,String>> for dynamic/real fields

    final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> field_lookups = ElasticsearchIndexUtils
            .parseDefaultMapping(default_mapping,
                    (CollidePolicy.new_type == Optional
                            .ofNullable(schema_config.search_technology_override().collide_policy())
                            .orElse(CollidePolicy.new_type))
                                    ? Optional.empty()
                                    : Optional.ofNullable(
                                            schema_config.search_technology_override().type_name_or_prefix()),
                    Optionals.of(() -> bucket.data_schema().search_index_schema()),
                    Optionals.of(() -> bucket.data_schema().document_schema()),
                    schema_config.search_technology_override(), mapper);

    // If a time field is present then adding the default mapping for it (overwrite @timestamp if that's the specified field):

    final Optional<JsonNode> time_mapping = Optional.ofNullable(schema_config.temporal_technology_override())
            .map(DataSchemaBean.TemporalSchemaBean::technology_override_schema)
            .map(t -> (Object) t.get("default_timefield_mapping"))
            .map(js -> mapper.convertValue(js, JsonNode.class));
    time_mapping.ifPresent(json -> {
        Optional.ofNullable(bucket.data_schema()).map(DataSchemaBean::temporal_schema)
                .filter(s -> Optional.ofNullable(s.enabled()).orElse(true)).map(t -> t.time_field())
                .ifPresent(time_field -> {
                    field_lookups.put(Either.left(time_field), json); //(MUTABLE CODE WARNING)
                });
    });

    final XContentBuilder test_result = getFullMapping(bucket, secondary_buffer, is_primary, schema_config,
            field_lookups, enabled_not_analyzed_field, enabled_analyzed_field, default_not_analyzed_field,
            default_analyzed_field, doc_schema, schema_config.search_technology_override(), mapper, index_type);

    return test_result;
}

From source file:fi.hsl.parkandride.core.service.PredictionService.java

@Scheduled(cron = "0 */5 * * * *") // every 5 minutes to match PredictionDao.PREDICTION_RESOLUTION
public void updatePredictions() {
    Optional<Lock> lock = Optional.empty();
    try {/* w  ww .j  a  v a  2  s  .co m*/
        lock = Optional.of(lockRepository.acquireLock("update-predictions", Duration.standardMinutes(2)));
        doUpdatePredictions();
    } catch (LockException e) {
        log.debug("Failed to get lock for updating predictions - another node updates them.");
        return;
    } finally {
        lock.ifPresent(l -> lockRepository.releaseLock(l));
    }
}

From source file:com.github.lukaszbudnik.dqueue.QueueClientImpl.java

protected void executeAndMeasureTime(NoArgVoidFunction function, String metricName) {
    Optional<Timer.Context> timer = Optional.ofNullable(metricRegistry).map(m -> m.timer(metricName).time());
    try {// w w  w . j a  v  a  2 s .co m
        function.apply();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        timer.ifPresent(Timer.Context::stop);
    }
}

From source file:com.github.lukaszbudnik.dqueue.QueueClientImpl.java

protected <R> R executeAndMeasureTime(NoArgFunction<R> function, String metricName) {
    Optional<Timer.Context> timer = Optional.ofNullable(metricRegistry).map(m -> m.timer(metricName).time());
    try {/*from   ww w  .  java  2  s  . c  om*/
        return function.apply();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        timer.ifPresent(Timer.Context::stop);
    }
}

From source file:nu.yona.server.device.service.DeviceService.java

@Transactional
public void postOpenAppEvent(UUID userId, UUID deviceId, Optional<OperatingSystem> operatingSystem,
        Optional<String> appVersion, int appVersionCode) {
    userService.updateUser(userId, userEntity -> {
        operatingSystem.ifPresent(os -> assertValidAppVersion(os, appVersion.get(), appVersionCode));

        LocalDate now = TimeUtil.utcNow().toLocalDate();
        UserDevice deviceEntity = getDeviceEntity(deviceId);
        DeviceAnonymized deviceAnonymizedEntity = deviceEntity.getDeviceAnonymized();

        setAppLastOpenedDateIfNewer(now, userEntity::getAppLastOpenedDate,
                () -> userEntity.setAppLastOpenedDate(now));
        setAppLastOpenedDateIfNewer(now, () -> Optional.of(deviceEntity.getAppLastOpenedDate()),
                () -> deviceEntity.setAppLastOpenedDate(now));
        operatingSystem.ifPresent(os -> setOperatingSystemIfWasUnknown(deviceEntity, os));
        setAppVersionIfDifferent(deviceAnonymizedEntity, appVersion, appVersionCode);
    });/*w ww.j a  va2  s.c o m*/
}

From source file:org.trustedanalytics.user.invite.rest.RegistrationsController.java

@ApiOperation(value = "Registers new user using security code received in email message.", notes = "Privilege level: Consmer of this endpoint requires a valid one-time security code")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = RegistrationModel.class),
        @ApiResponse(code = 400, message = "Invalid organization name."),
        @ApiResponse(code = 403, message = "Security code 'code' empty or null"),
        @ApiResponse(code = 409, message = "Invalid password (empty or too short)."),
        @ApiResponse(code = 409, message = "Organization already exists."),
        @ApiResponse(code = 409, message = "User already exists."),
        @ApiResponse(code = 500, message = "Internal server error, e.g. error connecting to CloudController") })
@RequestMapping(method = RequestMethod.POST)
public RegistrationModel addUser(@RequestBody RegistrationModel newUser,
        @RequestParam(value = "code", required = false) String code) {
    if (Strings.isNullOrEmpty(code)) {
        throw new InvalidSecurityCodeException("Security code empty or null");
    }/*from w w  w .  ja  v a  2 s.  co m*/
    SecurityCode sc = securityCodeService.verify(code);
    userPasswordValidator.validate(newUser.getPassword());
    Optional<OrgAndUserGuids> orgAndUserGuids = Optional.empty();
    String email = sc.getEmail();
    if (accessInvitationsService.getOrgCreationEligibility(email)) {
        orgAndUserGuids = invitationsService.createUser(email, newUser.getPassword(), newUser.getOrg());
    } else {
        invitationsService.createUser(email, newUser.getPassword());
    }
    securityCodeService.redeem(sc);
    accessInvitationsService.redeemAccessInvitations(email);
    orgAndUserGuids.ifPresent(guids -> {
        newUser.setOrgGuid(guids.getOrgGuid().toString());
        newUser.setUserGuid(guids.getUserGuid().toString());
    });
    return newUser;
}

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(
            infrastructure -> instanceCache.registerInfrastructureInstances(infrastructure, instancesCreated));

    return instancesCreated;
}

From source file:org.jboss.pnc.buildagent.client.BuildAgentClient.java

private void registerTextResponseConsumer(Optional<Consumer<String>> responseDataConsumer, Client client) {
    Consumer<String> responseConsumer = (string) -> {
        if ("% ".equals(string)) {
            log.info("Text consumer received command line 'ready'(%) marker.");
            onCommandPromptReady();//  ww w.  jav  a 2  s .  co  m
        } else {
            responseDataConsumer.ifPresent((rdc) -> rdc.accept(string));
            ;
        }
    };
    client.onStringMessage(responseConsumer);
}