Java Code Examples for java.util.Optional#ifPresentOrElse()

The following examples show how to use java.util.Optional#ifPresentOrElse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AdminChangeLogLevel.java    From besu with Apache License 2.0 7 votes vote down vote up
@Override
public JsonRpcResponse response(final JsonRpcRequestContext requestContext) {
  try {
    final Level logLevel = requestContext.getRequiredParameter(0, Level.class);
    final Optional<String[]> optionalLogFilters =
        requestContext.getOptionalParameter(1, String[].class);
    optionalLogFilters.ifPresentOrElse(
        logFilters ->
            Arrays.stream(logFilters).forEach(logFilter -> setLogLevel(logFilter, logLevel)),
        () -> setLogLevel("", logLevel));
    return new JsonRpcSuccessResponse(requestContext.getRequest().getId());
  } catch (InvalidJsonRpcParameters invalidJsonRpcParameters) {
    return new JsonRpcErrorResponse(
        requestContext.getRequest().getId(), JsonRpcError.INVALID_PARAMS);
  }
}
 
Example 2
Source File: AlertController.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private void validateLoadAlert(Long clusterId, Optional<Long> alertId, LoadAlertRequest json) {
    Cluster cluster = getClusterForWorkspace(clusterId);
    alertId.ifPresentOrElse(updateAlert -> validateAlertForUpdate(cluster, updateAlert, AlertType.LOAD),
            () -> {
                validateAccountEntitlement(cluster);
                validateSupportedHostGroup(cluster, json.getScalingPolicy().getHostGroup(), AlertType.LOAD);
                String requestHostGroup = json.getScalingPolicy().getHostGroup();
                cluster.getLoadAlerts().stream().map(LoadAlert::getScalingPolicy).map(ScalingPolicy::getHostGroup)
                        .filter(hostGroup -> hostGroup.equalsIgnoreCase(requestHostGroup)).findAny()
                        .ifPresent(hostGroup -> {
                            throw new BadRequestException(messagesService
                                    .getMessage(MessageCode.LOAD_CONFIG_ALREADY_DEFINED, List.of(cluster.getStackName(), requestHostGroup)));
                        });
                clusterProxyConfigurationService.getClusterProxyUrl()
                        .orElseThrow(() ->  new BadRequestException(
                                messagesService.getMessage(MessageCode.CLUSTER_PROXY_NOT_CONFIGURED, List.of(cluster.getStackName()))));
            });
}
 
Example 3
Source File: RecurringStateApplyJob.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Schedule highstate application.
 *
 * If the {@link RecurringAction} data is not found, clean the schedule.
 *
 * {@inheritDoc}
 */
public void execute(JobExecutionContext context) throws JobExecutionException {
    String scheduleName = context.getJobDetail().getKey().getName();
    Optional<RecurringAction> recurringAction = RecurringActionFactory.lookupByJobName(scheduleName);

    recurringAction.ifPresentOrElse(
            action ->  {
                if (action.isActive()) {
                    scheduleAction(context, action);
                }
                else {
                    log.debug(String.format("Action %s not active, skipping", action));
                }
            },
            () -> cleanSchedule(scheduleName)
    );
}
 
Example 4
Source File: EnvironmentServiceDecorator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public void prepareEnvironments(Set<ClusterTemplateViewV4Response> clusterTemplateViewV4Responses) {
    LOGGER.debug("Decorating with environment name the following cluster definition(s): {}",
            clusterTemplateViewV4Responses.stream().map(CompactViewV4Response::getName).collect(toSet()));
    Collection<SimpleEnvironmentResponse> responses = environmentClientService.list().getResponses();
    for (ClusterTemplateViewV4Response clusterTemplateViewV4Response : clusterTemplateViewV4Responses) {
        Optional<SimpleEnvironmentResponse> first = responses.stream()
                .filter(x -> x.getCrn().equals(clusterTemplateViewV4Response.getEnvironmentCrn()))
                .findFirst();
        first.ifPresentOrElse(simpleEnvironmentResponse -> clusterTemplateViewV4Response.setEnvironmentName(simpleEnvironmentResponse.getName()), () ->
                LOGGER.info("Unable to find environment name for cluster definition \"{}\"", clusterTemplateViewV4Response.getName()));
    }
}
 
Example 5
Source File: ResourceCheckSteps.java    From vividus with Apache License 2.0 5 votes vote down vote up
private ResourceValidation brokenResourceValidation(String pageURL, Optional<Exception> exception)
{
    ResourceValidation resourceValidation = new ResourceValidation();
    resourceValidation.setCheckStatus(CheckStatus.BROKEN);
    resourceValidation.setPageURL(pageURL);
    String message = "Unable to get page with URL: " + pageURL;
    exception.ifPresentOrElse(e -> softAssert.recordFailedAssertion(message, e),
        () -> softAssert.recordFailedAssertion(message + "; Response is received without body;"));
    return resourceValidation;
}
 
Example 6
Source File: AlertController.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void validateTimeAlert(Long clusterId, Optional<Long> alertId, TimeAlertRequest json) {
    Cluster cluster = getClusterForWorkspace(clusterId);
    alertId.ifPresentOrElse(updateAlert -> validateAlertForUpdate(cluster, updateAlert, AlertType.TIME),
            () -> {
                validateAccountEntitlement(cluster);
                validateSupportedHostGroup(cluster, json.getScalingPolicy().getHostGroup(), AlertType.TIME);
            });
    try {
        dateService.validateTimeZone(json.getTimeZone());
        dateService.getCronExpression(json.getCron());
    } catch (ParseException parseException) {
        throw new BadRequestException(parseException.getMessage(), parseException);
    }
}
 
Example 7
Source File: LdapConfigService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public void delete(String environmentCrn, String accountId, String clusterName) {
    Optional<LdapConfig> ldapConfig =
            ldapConfigRepository.findByAccountIdAndEnvironmentCrnAndClusterName(accountId, environmentCrn, clusterName);
    ldapConfig.ifPresentOrElse(this::delete, () -> {
        throw notFound("LdapConfig for environment", environmentCrn).get();
    });
}
 
Example 8
Source File: KerberosConfigService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public void delete(String environmentCrn, String accountId, String clusterName) {
    Optional<KerberosConfig> kerberosConfig =
            kerberosConfigRepository.findByAccountIdAndEnvironmentCrnAndClusterName(accountId, environmentCrn, clusterName);
    kerberosConfig.ifPresentOrElse(this::delete, () -> {
        throw notFound("KerberosConfig for environment", environmentCrn).get();
    });
}
 
Example 9
Source File: DockerImages.java    From vespa with Apache License 2.0 5 votes vote down vote up
/** Set the docker image for nodes of given type */
public void setDockerImage(NodeType nodeType, Optional<DockerImage> dockerImage) {
    if (nodeType.isDockerHost()) {
        throw new IllegalArgumentException("Setting docker image for " + nodeType + " nodes is unsupported");
    }
    try (Lock lock = db.lockDockerImages()) {
        Map<NodeType, DockerImage> dockerImages = db.readDockerImages();
        dockerImage.ifPresentOrElse(image -> dockerImages.put(nodeType, image),
                                    () -> dockerImages.remove(nodeType));
        db.writeDockerImages(dockerImages);
        createCache(); // Throw away current cache
        log.info("Set docker image for " + nodeType + " nodes to " + dockerImage.map(DockerImage::asString).orElse(null));
    }
}
 
Example 10
Source File: VersionDetection.java    From robozonky with Apache License 2.0 5 votes vote down vote up
private static void processVersion(Optional<String> version, AtomicReference<String> target, String unchanged,
        String changed, Function<String, ? extends GlobalEvent> eventSupplier) {
    version.ifPresentOrElse(newVersion -> {
        var oldVersion = target.getAndSet(newVersion);
        if (Objects.equals(newVersion, oldVersion)) {
            LOGGER.debug(unchanged, newVersion);
            return;
        }
        LOGGER.info(changed, newVersion);
        Events.global()
            .fire(eventSupplier.apply(newVersion));
    }, () -> target.set(null));
}
 
Example 11
Source File: Store.java    From teku with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<BeaconState> getBlockStateIfAvailable(final Bytes32 blockRoot) {
  readLock.lock();
  try {
    final Optional<BeaconState> state = Optional.ofNullable(block_states.get(blockRoot));
    state.ifPresentOrElse(s -> stateRequestCachedCounter.inc(), stateRequestMissCounter::inc);
    return state;
  } finally {
    readLock.unlock();
  }
}
 
Example 12
Source File: PeerRequiredLocalMessageHandler.java    From teku with Apache License 2.0 5 votes vote down vote up
@Override
public void onIncomingMessage(
    final Optional<Eth2Peer> maybePeer, final I message, final ResponseCallback<O> callback) {
  maybePeer.ifPresentOrElse(
      peer -> onIncomingMessage(peer, message, callback),
      () -> {
        LOG.trace(
            "Ignoring message of type {} because peer has disconnected", message.getClass());
        callback.completeWithUnexpectedError(new PeerDisconnectedException());
      });
}
 
Example 13
Source File: TestSolution2OptionalConditionalFetching.java    From java-katas with MIT License 5 votes vote down vote up
@Test
@DisplayName("perform action with value if non-empty else perform empty action")
@Tag("PASSING")
@Order(6)
public void ifPresentConsumeOrElseOtherAction() {
    AtomicInteger nonEmptyValueCounter = new AtomicInteger(0);

    Consumer<Integer> nonEmptyValueAction = x -> nonEmptyValueCounter.getAndAdd(x);
    Runnable alternateAction = nonEmptyValueCounter::getAndDecrement;

    Optional<Integer> nonEmptyIntegerOptional = Optional.of(10);

    /*
     * DONE:
     *  Add an ifPresentOrElse call to run either the nonEmptyValueAction or alternateAction
     *  (depending on whether the optional has a value or not)
     *  Check API: java.util.Optional.ifPresentOrElse(?, ?)
     */
    nonEmptyIntegerOptional.ifPresentOrElse(nonEmptyValueAction, alternateAction);

    assertEquals(10, nonEmptyValueCounter.get(), "");

    Optional<Integer> emptyIntegerOptional = Optional.ofNullable(null);

    /*
     * DONE:
     *  Add an ifPresentOrElse call to run either the nonEmptyValueAction or alternateAction
     *  (depending on whether the optional has a value or not)
     *  Check API: java.util.Optional.ifPresentOrElse(?, ?)
     */
    emptyIntegerOptional.ifPresentOrElse(nonEmptyValueAction, alternateAction);

    assertEquals(9, nonEmptyValueCounter.get(), "");
}
 
Example 14
Source File: Book.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
public void displayStatusAlsoPrefer() {

        // fetch an Optional prone to be empty
        Optional<String> status = Optional.empty();

        status.ifPresentOrElse(System.out::println,
                () -> System.out.println("Status not found ..."));
    }
 
Example 15
Source File: OptionalDemo.java    From Java-11-Cookbook-Second-Edition with MIT License 4 votes vote down vote up
private static void processIfPresentOrElse1(Optional<Integer> lotteryPrize){
    Consumer<Integer> weWon = prize -> checkResultAndShare(prize);
    Runnable weLost = () -> System.out.println("We've lost again...");
    lotteryPrize.ifPresentOrElse(weWon, weLost);
}
 
Example 16
Source File: OptionalDemo.java    From Java-11-Cookbook-Second-Edition with MIT License 4 votes vote down vote up
private static void processIfPresentOrElse2(Optional<Integer> lotteryPrize){
   lotteryPrize.ifPresentOrElse(weWon(), weLost());
}
 
Example 17
Source File: OptionalDemo.java    From Java-11-Cookbook-Second-Edition with MIT License 4 votes vote down vote up
private static void processOrGet(Optional<Integer> lotteryPrize){
    int prize = lotteryPrize.orElseGet(() -> 42);
    lotteryPrize.ifPresentOrElse(p -> checkResultAndShare(p),
            () -> System.out.println("Better " + prize + " than nothing..."));
}
 
Example 18
Source File: KerberosConfigService.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public void delete(String environmentCrn, String accountId) {
    Optional<KerberosConfig> kerberosConfig = kerberosConfigRepository.findByAccountIdAndEnvironmentCrnAndClusterNameIsNull(accountId, environmentCrn);
    kerberosConfig.ifPresentOrElse(this::delete, () -> {
        throw notFound("KerberosConfig for environment", environmentCrn).get();
    });
}
 
Example 19
Source File: OptionalDemo.java    From Java-11-Cookbook-Second-Edition with MIT License 4 votes vote down vote up
private static void processOrGet1(Optional<Integer> lotteryPrize){
    int prize = lotteryPrize.orElseGet(() -> 42);
    lotteryPrize.ifPresentOrElse(weWon(), better(prize));
}
 
Example 20
Source File: LdapConfigService.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public void delete(String environmentCrn, String accountId) {
    Optional<LdapConfig> ldapConfig = ldapConfigRepository.findByAccountIdAndEnvironmentCrnAndClusterNameIsNull(accountId, environmentCrn);
    ldapConfig.ifPresentOrElse(this::delete, () -> {
        throw notFound("LdapConfig for environment", environmentCrn).get();
    });
}