Example usage for java.util Optional orElse

List of usage examples for java.util Optional orElse

Introduction

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

Prototype

public T orElse(T other) 

Source Link

Document

If a value is present, returns the value, otherwise returns other .

Usage

From source file:ddf.catalog.transformer.input.geojson.GeoJsonInputTransformer.java

private MetacardImpl getMetacard(String propertyTypeName, Map<String, Object> properties)
        throws CatalogTransformerException {
    if (isEmpty(propertyTypeName) || metacardTypes == null) {
        LOGGER.debug("MetacardType specified in input is null or empty.  Trying all transformers in order...");
        Optional<MetacardImpl> first = inputTransformers == null ? Optional.of(new MetacardImpl())
                : inputTransformers.stream().map(service -> tryTransformers(properties, service))
                        .filter(Objects::nonNull).findFirst();
        return first.orElse(new MetacardImpl());
    } else {/*from www.  j a v  a 2s.c  om*/
        MetacardType metacardType = metacardTypes.stream()
                .filter(type -> type.getName().equals(propertyTypeName)).findFirst()
                .orElseThrow(() -> new CatalogTransformerException(
                        "MetacardType specified in input has not been registered with the system."
                                + " Cannot parse input. MetacardType name: " + propertyTypeName));

        LOGGER.debug("Found registered MetacardType: {}", propertyTypeName);
        return new MetacardImpl(metacardType);
    }
}

From source file:org.ow2.proactive.workflow_catalog.rest.service.WorkflowRevisionService.java

@Transactional
public WorkflowMetadata createWorkflowRevision(Long bucketId, Optional<Long> workflowId,
        ProActiveWorkflowParserResult proActiveWorkflowParserResult, Optional<String> layout,
        byte[] proActiveWorkflowXmlContent) {
    Bucket bucket = findBucket(bucketId);

    Workflow workflow = null;/*  w ww .  j  a v  a  2s.  c  o  m*/
    WorkflowRevision workflowRevision;
    String layoutValue = layout.orElse("");

    long revisionNumber = 1;

    if (workflowId.isPresent()) {
        workflow = findWorkflow(workflowId.get());
        revisionNumber = workflow.getLastRevisionId() + 1;
    }

    workflowRevision = new WorkflowRevision(bucketId, revisionNumber,
            proActiveWorkflowParserResult.getJobName(), proActiveWorkflowParserResult.getProjectName(),
            LocalDateTime.now(), layoutValue, proActiveWorkflowXmlContent);

    workflowRevision.addGenericInformation(
            createEntityGenericInformation(proActiveWorkflowParserResult.getGenericInformation()));

    workflowRevision.addVariables(createEntityVariable(proActiveWorkflowParserResult.getVariables()));

    workflowRevision = workflowRevisionRepository.save(workflowRevision);

    if (!workflowId.isPresent()) {
        workflow = new Workflow(bucket, workflowRevision);
    } else {
        workflow.addRevision(workflowRevision);
    }

    workflowRepository.save(workflow);

    return new WorkflowMetadata(workflowRevision);
}

From source file:org.pdfsam.split.SplitModule.java

@Override
protected Builder<? extends AbstractSplitByPageParameters> getBuilder(Consumer<String> onError) {
    Optional<SinglePdfSourceMultipleOutputParametersBuilder<? extends AbstractSplitByPageParameters>> builder = Optional
            .ofNullable(splitOptions.getBuilder(onError));
    builder.ifPresent(b -> {//from   w w w .  j a v  a  2s .  c  o m
        selectionPane.apply(b, onError);
        destinationDirectoryField.apply(b, onError);
        destinationPane.apply(b, onError);
        prefix.apply(b, onError);
    });
    return builder.orElse(null);
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.azure.vm.AzureVMsProvider.java

private List<Creatable<VirtualMachine>> prepareCreatableVirtualMachines(Azure azureService,
        Optional<Options> options, Region region, ResourceGroup resourceGroup, String instanceTag,
        Instance instance, VirtualMachineCustomImage image, Optional<Boolean> optionalStaticPublicIP) {

    // Prepare a new virtual private network (same for all VMs)
    Optional<String> optionalPrivateNetworkCIDR = options.map(Options::getPrivateNetworkCIDR);
    Creatable<Network> creatableVirtualNetwork = azureProviderNetworkingUtils.prepareVirtualNetwork(
            azureService, region, resourceGroup, createUniqueVirtualNetworkName(instanceTag),
            optionalPrivateNetworkCIDR.orElse(defaultPrivateNetworkCidr));

    // Get existing virtual private network if specified
    Optional<Network> optionalVirtualNetwork = options.map(Options::getSubnetId)
            .map(subnetId -> azureProviderUtils.searchVirtualNetworkByName(azureService, subnetId).get());

    // Prepare a new  security group (same for all VMs)
    Creatable<NetworkSecurityGroup> creatableNetworkSecurityGroup = azureProviderNetworkingUtils
            .prepareProactiveNetworkSecurityGroup(azureService, region, resourceGroup,
                    createUniqueSecurityGroupName(instance.getTag()));

    // Get existing security group if specified
    Optional<NetworkSecurityGroup> optionalNetworkSecurityGroup = options.map(Options::getSecurityGroupNames)
            .map(secGrpNames -> secGrpNames.get(0)).map(secGrpName -> azureProviderUtils
                    .searchNetworkSecurityGroupByName(azureService, secGrpName).get());

    // Get existing public IP address if specified
    Optional<PublicIpAddress> optionalPublicIpAddress = options.map(Options::getPublicIpAddress)
            .map(publicIpAddress -> azureProviderUtils.searchPublicIpAddressByIp(azureService, publicIpAddress)
                    .get());/*from www . j  av  a  2 s. c  om*/

    return IntStream
            .rangeClosed(1,
                    Integer.valueOf(Optional.ofNullable(instance.getNumber()).orElse(SINGLE_INSTANCE_NUMBER)))
            .mapToObj(instanceNumber -> {
                // Create a new public IP address (one per VM)
                String publicIPAddressName = createUniquePublicIPName(
                        createUniqueInstanceTag(instanceTag, instanceNumber));
                Creatable<PublicIpAddress> creatablePublicIpAddress = azureProviderNetworkingUtils
                        .preparePublicIPAddress(azureService, region, resourceGroup, publicIPAddressName,
                                optionalStaticPublicIP.orElse(DEFAULT_STATIC_PUBLIC_IP));

                // Prepare a new network interface (one per VM)
                String networkInterfaceName = createUniqueNetworkInterfaceName(
                        createUniqueInstanceTag(instanceTag, instanceNumber));
                Creatable<NetworkInterface> creatableNetworkInterface = azureProviderNetworkingUtils
                        .prepareNetworkInterface(azureService, region, resourceGroup, networkInterfaceName,
                                creatableVirtualNetwork, optionalVirtualNetwork.orElse(null),
                                creatableNetworkSecurityGroup, optionalNetworkSecurityGroup.orElse(null),
                                creatablePublicIpAddress,
                                instanceNumber == 1 ? optionalPublicIpAddress.orElse(null) : null);

                return prepareVirtualMachine(instance, azureService, resourceGroup, region,
                        createUniqueInstanceTag(instanceTag, instanceNumber), image, creatableNetworkInterface);
            }).collect(Collectors.toList());
}

From source file:ch.ralscha.extdirectspring.provider.RemoteProviderOptional.java

@ExtDirectMethod(value = ExtDirectMethodType.STORE_READ, group = "optional")
public ExtDirectStoreResult<Row> storeRead1(ExtDirectStoreReadRequest request, Locale locale,
        @RequestParam(value = "id") Optional<Integer> id) {

    if (id.isPresent()) {
        assertThat(id.get()).isEqualTo(10);
        assertThat(request.getParams().size()).isEqualTo(1);
        assertThat(request.getParams()).contains(entry("id", 10));
    } else {/*from ww  w .j  av  a 2  s .  c o  m*/
        assertThat(id.orElse(20)).isEqualTo(20);
        assertThat(request.getParams().isEmpty()).isTrue();
    }
    assertThat(locale).isEqualTo(Locale.ENGLISH);

    return RemoteProviderStoreRead.createExtDirectStoreResult(request, ":" + id.orElse(20) + ";" + locale);
}

From source file:org.kie.appformer.ala.wildfly.executor.AppFormerProvisioningHelper.java

public WildflyDataSourceDef findWildflyDataSource(String host, int port, String user, String password,
        String realm, String dataSourceName) throws Exception {
    Optional<WildflyDataSourceDef> optionalDS = findWildflyDataSources(host, port, user, password, realm,
            dataSourceName).stream()//from  www.ja  va  2  s  .  c o m
                    .filter(wildflyDataSourceDef -> wildflyDataSourceDef.getName().equals(dataSourceName))
                    .findFirst();
    return optionalDS.orElse(null);
}

From source file:org.cyberjos.jcconf2016.node.HazelcastHelper.java

/**
 * Sets the given node to be the master node.
 *
 * @param cloudNode the node to become master
 * @return {@code true} if the given node becomes the master node
 *         successfully//w w  w  .  jav  a 2s  .c  om
 * @throws NullPointerException if the given node is {@code null}
 */
public synchronized boolean setMaster(final CloudNode cloudNode) {
    Objects.requireNonNull(cloudNode, "The given cloud node must not be null.");

    final Lock lock = hazelcastHolder.getInstance().getLock("my-distributed-lock");
    lock.lock();

    try {
        final String nodeName = cloudNode.getName();
        final Optional<NodeRecord> optional = this.getMasterNodeRecord();
        logger.info("[{}] Ensure the master node: {}", nodeName, optional.orElse(null));

        if (optional.isPresent()) {
            final NodeRecord masterRecord = optional.get();
            final long count = hazelcastHolder.getInstance().getCluster().getMembers().stream()
                    .filter(member -> StringUtils.equals(masterRecord.getMemberId(), member.getUuid())).count();

            if (count != 0) {
                logger.warn("[{}] The master node has already existed: {}", nodeName, masterRecord);
                return false;
            }

            this.unregisterNode(masterRecord.getNodeName());
        }

        final NodeRecord newMasterRecord = HazelcastHelper.<String, NodeRecord>getMap(ACTIVE_NODES)
                .get(nodeName);
        HazelcastHelper.getAtomicReference(MASTER_NODE).set(newMasterRecord);
        logger.info("[{}] This node becomes the new master node: {}", nodeName, newMasterRecord);

        if (WORKING_MODE) {
            this.runProducer(cloudNode);
        }
    } finally {
        lock.unlock();
    }

    return true;
}

From source file:com.netflix.genie.core.jpa.services.JpaClusterServiceImpl.java

private void updateAndSaveClusterEntity(final ClusterEntity clusterEntity, final Cluster updateCluster) {
    clusterEntity.setName(updateCluster.getName());
    clusterEntity.setUser(updateCluster.getUser());
    clusterEntity.setVersion(updateCluster.getVersion());
    final Optional<String> description = updateCluster.getDescription();
    clusterEntity.setDescription(description.orElse(null));
    clusterEntity.setStatus(updateCluster.getStatus());
    clusterEntity.setConfigs(updateCluster.getConfigs());
    clusterEntity.setDependencies(updateCluster.getDependencies());
    clusterEntity.setTags(updateCluster.getTags());
    final Optional<String> setupFile = updateCluster.getSetupFile();
    clusterEntity.setSetupFile(setupFile.orElse(null));

    this.clusterRepo.save(clusterEntity);
}

From source file:jobhunter.gui.FXMLController.java

private void openJobForm(final Optional<Job> job) {
    JobFormController.create(bundle).setJob(job.orElse(null)).show();
}

From source file:org.openmhealth.shim.googlefit.mapper.GoogleFitCaloriesBurnedDataPointMapper.java

@Override
protected Optional<DataPoint<CaloriesBurned>> asDataPoint(JsonNode listNode) {

    JsonNode listValueNode = asRequiredNode(listNode, "value");
    // TODO isn't this just "value.fpVal"?
    double caloriesBurnedValue = asRequiredDouble(listValueNode.get(0), "fpVal");

    CaloriesBurned.Builder caloriesBurnedBuilder = new CaloriesBurned.Builder(
            new KcalUnitValue(KILOCALORIE, caloriesBurnedValue));

    setEffectiveTimeFrameIfPresent(caloriesBurnedBuilder, listNode);

    CaloriesBurned caloriesBurned = caloriesBurnedBuilder.build();
    Optional<String> originDataSourceId = asOptionalString(listNode, "originDataSourceId");

    // Google Fit calories burned endpoint returns calories burned by basal metabolic rate (BMR), however these
    // are not activity related calories burned so we do not create a datapoint for values from this source
    if (originDataSourceId.isPresent()) {
        if (originDataSourceId.get().contains("bmr")) {
            return Optional.empty();
        }/*from  w w  w .  jav a  2  s .  c o  m*/
    }

    return Optional.of(newDataPoint(caloriesBurned, originDataSourceId.orElse(null)));
}