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:org.sonar.server.setting.ws.SetAction.java

private void commonChecks(SetRequest request, Optional<ComponentDto> component) {
    checkValueIsSet(request);/*  www.  j a  v a 2  s . c om*/
    SettingData settingData = new SettingData(request.getKey(), valuesFromRequest(request),
            component.orElse(null));
    ImmutableList.of(validations.scope(), validations.qualifier(), validations.valueType())
            .forEach(validation -> validation.accept(settingData));
}

From source file:org.zanata.magpie.service.PersistentTranslationService.java

/**
 * See if the document has the text flow in database already. If not, try to
 * search same content hash from other documents. If any is found, try to
 * copy text flow and text flow target. If none is found, return empty.
 *
 * @param document/*from w w w .  j av  a  2 s.c o m*/
 *            current document
 * @param fromLocale
 *            from locale
 * @param toLocale
 *            to locale
 * @param backendID
 *            translation provider
 * @param contentHash
 *            text flow content hash
 * @return optional text flow that has the matching content hash
 */
private Optional<TextFlow> tryFindTextFlowByContentHashFromDB(@NotNull Document document,
        @NotNull Locale fromLocale, @NotNull Locale toLocale, @NotNull BackendID backendID,
        String contentHash) {
    TextFlow matchedHashTf = document.getTextFlows().get(contentHash);
    if (matchedHashTf == null) {
        // we don't have text flow for this document yet,
        // now try to search similar text flow from database
        Optional<TextFlow> tfCopy = tryCopyTextFlowAndTargetFromDB(document, fromLocale, toLocale, contentHash,
                backendID);

        matchedHashTf = tfCopy.orElse(null);
    }
    return Optional.ofNullable(matchedHashTf);
}

From source file:ee.ria.xroad.opmonitordaemon.HealthDataRequestHandler.java

@Override
public void handle(SoapMessageImpl requestSoap, OutputStream out, Consumer<String> contentTypeCallback)
        throws Exception {
    log.trace("handle()");

    ClientId clientId = requestSoap.getClient();
    GetSecurityServerHealthDataType requestData = getRequestData(requestSoap,
            GetSecurityServerHealthDataType.class);

    Optional<ClientId> provider = Optional.ofNullable(requestData.getFilterCriteria())
            .map(FilterCriteriaType::getClient);

    log.debug("Handle getSecurityServerHealthData: clientId: {}, " + "filterCriteria.client: {}", clientId,
            provider.orElse(null));

    SoapMessageImpl response = createResponse(requestSoap, buildHealthDataResponse(provider));

    contentTypeCallback.accept(response.getContentType());
    out.write(response.getBytes());//from  w  ww.  ja v  a2  s .  c  om
}

From source file:org.apache.metron.parsers.topology.ParserTopologyBuilder.java

/**
 * Create a bolt that parses input from a sensor.
 *
 * @param zookeeperUrl Zookeeper URL//from w ww.  j  a  v a2  s .c o m
 * @param brokerUrl    Kafka Broker URL
 * @param sensorTypeToParserConfig
 * @param configs
 * @return A Storm bolt that parses input from a sensor
 */
private static ParserBolt createParserBolt(String zookeeperUrl, Optional<String> brokerUrl,
        Map<String, SensorParserConfig> sensorTypeToParserConfig, Optional<String> securityProtocol,
        ParserConfigurations configs, Optional<String> outputTopic) {

    Map<String, ParserComponents> parserBoltConfigs = new HashMap<>();
    for (Entry<String, SensorParserConfig> entry : sensorTypeToParserConfig.entrySet()) {
        String sensorType = entry.getKey();
        SensorParserConfig parserConfig = entry.getValue();
        // create message parser
        MessageParser<JSONObject> parser = ReflectionUtils.createInstance(parserConfig.getParserClassName());
        parser.configure(parserConfig.getParserConfig());

        // create message filter
        MessageFilter<JSONObject> filter = null;
        if (!StringUtils.isEmpty(parserConfig.getFilterClassName())) {
            filter = Filters.get(parserConfig.getFilterClassName(), parserConfig.getParserConfig());
        }

        // create a writer
        AbstractWriter writer;
        if (parserConfig.getWriterClassName() == null) {

            // if not configured, use a sensible default
            writer = createKafkaWriter(brokerUrl, zookeeperUrl, securityProtocol)
                    .withTopic(outputTopic.orElse(Constants.ENRICHMENT_TOPIC));

        } else {
            writer = ReflectionUtils.createInstance(parserConfig.getWriterClassName());
        }

        // configure it
        writer.configure(sensorType, new ParserWriterConfiguration(configs));

        // create a writer handler
        WriterHandler writerHandler = createWriterHandler(writer);

        ParserComponents components = new ParserComponents(parser, filter, writerHandler);
        parserBoltConfigs.put(sensorType, components);
    }

    return new ParserBolt(zookeeperUrl, parserBoltConfigs);
}

From source file:com.okta.scim.SingleUserController.java

/**
 * Output custom error message with response code
 *
 * @param message Scim error message/*from   w  w  w  .j a  va 2  s.c  om*/
 * @param status_code Response status code
 * @return JSON {@link Map} of {@link User}
 */
public Map scimError(String message, Optional<Integer> status_code) {

    Map<String, Object> returnValue = new HashMap<>();
    List<String> schemas = new ArrayList<>();
    schemas.add("urn:ietf:params:scim:api:messages:2.0:Error");
    returnValue.put("schemas", schemas);
    returnValue.put("detail", message);

    // Set default to 500
    returnValue.put("status", status_code.orElse(500));
    return returnValue;
}

From source file:nu.yona.server.goals.service.GoalService.java

private void broadcastGoalChangeMessage(User userEntity, ActivityCategory activityCategoryOfChangedGoal,
        GoalChangeMessage.Change change, Optional<String> message) {
    messageService.broadcastMessageToBuddies(UserAnonymizedDto.createInstance(userEntity.getAnonymized()),
            () -> GoalChangeMessage.createInstance(BuddyInfoParameters.createInstance(userEntity),
                    activityCategoryOfChangedGoal, change, message.orElse(null)));
}

From source file:com.blackducksoftware.integration.hub.detect.configuration.DetectConfiguration.java

private DetectProperty fromOverrideToDeprecated(final DetectProperty detectProperty) {
    final Optional<DetectProperty> found = DetectPropertyDeprecations.PROPERTY_OVERRIDES.entrySet().stream()
            .filter(it -> it.getValue().equals(detectProperty)).map(it -> it.getKey()).findFirst();

    return found.orElse(null);
}

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

@ExtDirectMethod(value = ExtDirectMethodType.TREE_LOAD, group = "optional")
public List<Node> treeLoad1(@RequestParam("node") Optional<String> node, HttpServletResponse response,
        final HttpServletRequest request, @RequestParam Optional<String> foo,
        @CookieValue Optional<String> theCookie, final HttpSession session, Locale locale,
        Principal principal) {/*  w  w  w. j ava2  s  .c o m*/

    return RemoteProviderTreeLoad.createTreeList(node.get(),
            ":" + foo.orElse("defaultValue2") + ";" + theCookie.orElse("defaultCookieValue") + ";"
                    + (response != null) + ";" + (request != null) + ";" + (session != null) + ";" + locale);
}

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

private Creatable<VirtualMachine> prepareVitualMachine(Instance instance, Azure azureService,
        ResourceGroup resourceGroup, Region region, String instanceTag, VirtualMachineCustomImage image,
        Creatable<NetworkInterface> creatableNetworkInterface) {

    // Configure the VM depending on the OS type
    VirtualMachine.DefinitionStages.WithFromImageCreateOptionsManaged creatableVirtualMachineWithImage;
    OperatingSystemTypes operatingSystemType = image.osDiskImage().osType();
    if (operatingSystemType.equals(OperatingSystemTypes.LINUX)) {
        creatableVirtualMachineWithImage = configureLinuxVirtualMachine(azureService, instanceTag, region,
                resourceGroup, instance.getCredentials(), image, creatableNetworkInterface);
    } else if (operatingSystemType.equals(OperatingSystemTypes.WINDOWS)) {
        creatableVirtualMachineWithImage = configureWindowsVirtualMachine(azureService, instanceTag, region,
                resourceGroup, instance.getCredentials(), image, creatableNetworkInterface);
    } else {//from   w ww  .  j  a v  a  2 s  . c  om
        throw new RuntimeException(
                "ERROR Operating System of type '" + operatingSystemType.toString() + "' is not yet supported");
    }

    // Set VM size (or type) and name of OS' disk
    Optional<String> optionalHardwareType = Optional.ofNullable(instance.getHardware()).map(Hardware::getType);
    VirtualMachine.DefinitionStages.WithCreate creatableVMWithSize = creatableVirtualMachineWithImage
            .withSize(new VirtualMachineSizeTypes(optionalHardwareType.orElse(DEFAULT_VM_SIZE.toString())))
            .withOsDiskName(createUniqOSDiskName(instanceTag));

    // Add init script(s) using dedicated Microsoft extension
    Optional.ofNullable(instance.getInitScript()).map(InstanceScript::getScripts).ifPresent(scripts -> {
        if (scripts.length > 0) {
            StringBuilder concatenatedScripts = new StringBuilder();
            Lists.newArrayList(scripts)
                    .forEach(script -> concatenatedScripts.append(script).append(SCRIPT_SEPARATOR));
            creatableVMWithSize.defineNewExtension(createUniqueScriptName(instanceTag))
                    .withPublisher(SCRIPT_EXTENSION_PUBLISHER).withType(SCRIPT_EXTENSION_TYPE)
                    .withVersion(SCRIPT_EXTENSION_VERSION).withMinorVersionAutoUpgrade()
                    .withPublicSetting(SCRIPT_EXTENSION_CMD_KEY, concatenatedScripts.toString()).attach();
        }
    });

    // Set tags
    return creatableVMWithSize.withTags(tagManager.retrieveAllTags(instance.getOptions()).stream()
            .collect(Collectors.toMap(Tag::getKey, Tag::getValue)));
}

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);//from ww w.j a  v  a2s.c o m
    classMappingOpt.ifPresent(classMapping -> mergedClassesMapping.put(superType, classMapping));
    return classMappingOpt.orElse(null);
}