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.jspare.jsdbc.JsdbcTransportImpl.java

@Override
public String execute(DataSource datasource, Credential credential, Optional<Domain> domain, String operation,
        int method, String data) throws JsdbcException {

    if (datasource == null) {

        throw new JsdbcException("DataSource not loaded");
    }/*from   w w w  .ja  va2 s .c  o m*/

    try {

        Request request = null;
        org.apache.http.client.fluent.Response response = null;

        String uriAddress = getUrlConnection(datasource, operation,
                Optional.of(domain.orElse(Domain.of(StringUtils.EMPTY)).domain()));
        if (method == RETRIEVE) {
            request = Request.Get(new URIBuilder(uriAddress).build().toString());
        } else if (method == SEND) {
            request = Request.Post(new URIBuilder(uriAddress).build().toString()).bodyString(data,
                    ContentType.APPLICATION_JSON);
        } else {
            throw new JsdbcException("Method called is not mapped");
        }
        request.addHeader(AGENT_KEY, AGENT);

        response = buildAuthentication(request, datasource, credential).execute();

        HttpResponse httpResponse = response.returnResponse();

        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode < HttpStatus.SC_OK || statusCode >= HttpStatus.SC_MULTIPLE_CHOICES) {

            if (statusCode == HttpStatus.SC_BAD_REQUEST) {

                throw new JsdbcException("Authorization error, validate your credentials.");
            }
            if (statusCode == HttpStatus.SC_FORBIDDEN) {

                throw new JsdbcException("Forbidden access, validate your user roles.");
            }

            String content = IOUtils.toString(httpResponse.getEntity().getContent());

            ErrorResult result = my(Serializer.class).fromJSON(content, ErrorResult.class);
            throw new CommandFailException(result);
        }

        return IOUtils.toString(httpResponse.getEntity().getContent());

    } catch (Exception e) {

        log.error(e.getMessage(), e);
        throw new JsdbcException("JSDB Server Error");
    }
}

From source file:alfio.controller.api.admin.CheckInApiController.java

@RequestMapping(value = "/check-in/{eventName}/offline-identifiers", method = GET)
public List<Integer> getOfflineIdentifiers(@PathVariable("eventName") String eventName,
        @RequestParam(value = "changedSince", required = false) Long changedSince, HttpServletResponse resp,
        Principal principal) {/*from ww w . j av a  2s.  c o  m*/
    Date since = changedSince == null ? new Date(0) : DateUtils.addSeconds(new Date(changedSince), -1);
    Optional<List<Integer>> ids = optionally(() -> eventManager.getSingleEvent(eventName, principal.getName()))
            .filter(checkInManager.isOfflineCheckInEnabled())
            .map(event -> checkInManager.getAttendeesIdentifiers(event, since, principal.getName()));

    resp.setHeader(ALFIO_TIMESTAMP_HEADER, ids.isPresent() ? Long.toString(new Date().getTime()) : "0");
    return ids.orElse(Collections.emptyList());
}

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

protected GoalDto(UUID id, Optional<LocalDateTime> creationTime, Optional<LocalDateTime> endTime,
        UUID activityCategoryId, boolean mandatory) {
    Objects.requireNonNull(creationTime);
    this.id = id;
    this.setActivityCategoryId(activityCategoryId);
    this.mandatory = mandatory;

    // not using Optional as field here because of implementing Serializable
    // see//w ww  .j  av  a2  s .c  o  m
    // http://stackoverflow.com/questions/24547673/why-java-util-optional-is-not-serializable-how-to-serialize-the-object-with-suc
    this.creationTime = creationTime.orElse(null);
    this.endTime = endTime.orElse(null);
}

From source file:org.onosproject.net.intent.impl.compiler.OpticalCircuitIntentCompiler.java

private OchPort findAvailableOchPort(ConnectPoint oduPort) {
    // First see if the port mappings are constrained
    ConnectPoint ochCP = staticPort(oduPort);

    if (ochCP != null) {
        OchPort ochPort = (OchPort) deviceService.getPort(ochCP.deviceId(), ochCP.port());
        Optional<IntentId> intentId = resourceService
                .getResourceAllocation(new ResourcePath(ochCP.deviceId(), ochCP.port()))
                .map(ResourceAllocation::consumer).filter(x -> x instanceof IntentId).map(x -> (IntentId) x);

        if (isAvailable(intentId.orElse(null))) {
            return ochPort;
        }/*  w  w  w  . j  ava 2  s  . c om*/
    }

    // No port constraints, so find any port that works
    List<Port> ports = deviceService.getPorts(oduPort.deviceId());

    for (Port port : ports) {
        if (!(port instanceof OchPort)) {
            continue;
        }

        Optional<IntentId> intentId = resourceService
                .getResourceAllocation(new ResourcePath(oduPort.deviceId(), port.number()))
                .map(ResourceAllocation::consumer).filter(x -> x instanceof IntentId).map(x -> (IntentId) x);
        if (isAvailable(intentId.orElse(null))) {
            return (OchPort) port;
        }
    }

    return null;
}

From source file:com.devicehive.service.DeviceClassService.java

@Transactional
public DeviceClassWithEquipmentVO createOrUpdateDeviceClass(Optional<DeviceClassUpdate> deviceClass,
        Set<DeviceClassEquipmentVO> customEquipmentSet) {
    DeviceClassWithEquipmentVO stored;/*from   w  w w  .  ja  v  a 2 s. c o m*/
    //use existing
    if (deviceClass == null || !deviceClass.isPresent()) {
        return null;
    }
    //check is already done
    DeviceClassUpdate deviceClassUpdate = deviceClass.orElse(null);
    DeviceClassWithEquipmentVO deviceClassFromMessage = deviceClassUpdate.convertTo();
    if (deviceClassFromMessage.getId() != null) {
        stored = deviceClassDao.find(deviceClassFromMessage.getId());
    } else {
        stored = deviceClassDao.findByName(deviceClassFromMessage.getName());
    }
    if (stored != null) {
        if (!stored.getIsPermanent()) {
            deviceClassUpdate.setEquipment(Optional.ofNullable(customEquipmentSet));
            update(stored.getId(), deviceClassUpdate);
        }
        return stored;
    } else {
        return addDeviceClass(deviceClassFromMessage);
    }
}

From source file:com.ikanow.aleph2.management_db.services.DataBucketStatusCrudService.java

@Override
public ManagementFuture<Long> updateObjectsBySpec(final QueryComponent<DataBucketStatusBean> spec,
        final Optional<Boolean> upsert, final UpdateComponent<DataBucketStatusBean> update) {
    if (upsert.orElse(false)) {
        throw new RuntimeException("This method is not supported with upsert set and true");
    }/*from   w w w .  j  a  va 2s  .  co  m*/

    final CompletableFuture<Cursor<DataBucketStatusBean>> affected_ids = _underlying_data_bucket_status_db.get()
            .getObjectsBySpec(spec, Arrays.asList(
                    BeanTemplateUtils.from(DataBucketStatusBean.class).field(DataBucketStatusBean::_id)), true);

    try {
        return MgmtCrudUtils
                .applyCrudPredicate(affected_ids, status -> this.updateObjectById(status._id(), update))._1();
    } catch (Exception e) {
        // This is a serious enough exception that we'll just leave here
        return FutureUtils.createManagementFuture(FutureUtils.returnError(e));
    }
}

From source file:com.ikanow.aleph2.storage_service_hdfs.services.HfdsDataWriteService.java

/** User constructor
 * @param bucket//from w w w.j  av  a 2 s .com
 */
public HfdsDataWriteService(final DataBucketBean bucket, final IGenericDataService parent,
        final IStorageService.StorageStage stage, final Optional<String> job_name,
        final IStorageService storage_service, final Optional<String> secondary_buffer) {
    _bucket = bucket;
    _stage = stage;
    _buffer_name = secondary_buffer.orElse(IStorageService.PRIMARY_BUFFER_SUFFIX);
    _storage_service = storage_service;
    _job_name = job_name;
    _dfs = storage_service.getUnderlyingPlatformDriver(FileContext.class, Optional.empty()).get();
    _parent = parent;
}

From source file:org.csanchez.jenkins.plugins.kubernetes.PodTemplateBuilder.java

/**
 * Create a Pod object from a PodTemplate
 *///w ww  .j  a  va  2  s  .c o  m
public Pod build() {

    // Build volumes and volume mounts.
    Map<String, Volume> volumes = new HashMap<>();
    Map<String, VolumeMount> volumeMounts = new HashMap<>();

    int i = 0;
    for (final PodVolume volume : template.getVolumes()) {
        final String volumeName = "volume-" + i;
        //We need to normalize the path or we can end up in really hard to debug issues.
        final String mountPath = substituteEnv(
                Paths.get(volume.getMountPath()).normalize().toString().replace("\\", "/"));
        if (!volumeMounts.containsKey(mountPath)) {
            volumeMounts.put(mountPath, new VolumeMountBuilder() //
                    .withMountPath(mountPath).withName(volumeName).withReadOnly(false).build());
            volumes.put(volumeName, volume.buildVolume(volumeName));
            i++;
        }
    }

    if (template.getWorkspaceVolume() != null) {
        LOGGER.log(Level.FINE, "Adding workspace volume from template: {0}",
                template.getWorkspaceVolume().toString());
        volumes.put(WORKSPACE_VOLUME_NAME, template.getWorkspaceVolume().buildVolume(WORKSPACE_VOLUME_NAME));
    } else {
        // add an empty volume to share the workspace across the pod
        LOGGER.log(Level.FINE, "Adding empty workspace volume");
        volumes.put(WORKSPACE_VOLUME_NAME,
                new VolumeBuilder().withName(WORKSPACE_VOLUME_NAME).withNewEmptyDir().endEmptyDir().build());
    }

    Map<String, Container> containers = new HashMap<>();
    // containers from pod template
    for (ContainerTemplate containerTemplate : template.getContainers()) {
        containers.put(containerTemplate.getName(),
                createContainer(containerTemplate, template.getEnvVars(), volumeMounts.values()));
    }

    MetadataNested<PodBuilder> metadataBuilder = new PodBuilder().withNewMetadata();
    if (slave != null) {
        metadataBuilder.withName(substituteEnv(slave.getNodeName()));
    }

    Map<String, String> labels = new HashMap<>();
    if (slave != null) {
        labels.putAll(slave.getKubernetesCloud().getLabels());
    }
    labels.putAll(template.getLabelsMap());
    if (!labels.isEmpty()) {
        metadataBuilder.withLabels(labels);
    }

    Map<String, String> annotations = getAnnotationsMap(template.getAnnotations());
    if (!annotations.isEmpty()) {
        metadataBuilder.withAnnotations(annotations);
    }

    SpecNested<PodBuilder> builder = metadataBuilder.endMetadata().withNewSpec();

    if (template.getActiveDeadlineSeconds() > 0) {
        builder = builder.withActiveDeadlineSeconds(Long.valueOf(template.getActiveDeadlineSeconds()));
    }

    if (!volumes.isEmpty()) {
        builder.withVolumes(volumes.values().toArray(new Volume[volumes.size()]));
    }
    if (template.getServiceAccount() != null) {
        builder.withServiceAccount(substituteEnv(template.getServiceAccount()));
    }

    List<LocalObjectReference> imagePullSecrets = template.getImagePullSecrets().stream()
            .map((x) -> x.toLocalObjectReference()).collect(Collectors.toList());
    if (!imagePullSecrets.isEmpty()) {
        builder.withImagePullSecrets(imagePullSecrets);
    }

    Map<String, String> nodeSelector = getNodeSelectorMap(template.getNodeSelector());
    if (!nodeSelector.isEmpty()) {
        builder.withNodeSelector(nodeSelector);
    }

    builder.withContainers(containers.values().toArray(new Container[containers.size()]));
    Pod pod = builder.endSpec().build();

    // merge with the yaml
    String yaml = template.getYaml();
    if (!StringUtils.isBlank(yaml)) {
        Pod podFromYaml = parseFromYaml(yaml);
        pod = combine(podFromYaml, pod);
    }

    // Apply defaults

    // default restart policy
    if (StringUtils.isBlank(pod.getSpec().getRestartPolicy())) {
        pod.getSpec().setRestartPolicy("Never");
    }

    // default jnlp container
    Optional<Container> jnlpOpt = pod.getSpec().getContainers().stream()
            .filter(c -> JNLP_NAME.equals(c.getName())).findFirst();
    Container jnlp = jnlpOpt.orElse(new ContainerBuilder().withName(JNLP_NAME).build());
    if (!jnlpOpt.isPresent()) {
        pod.getSpec().getContainers().add(jnlp);
    }
    if (StringUtils.isBlank(jnlp.getImage())) {
        jnlp.setImage(DEFAULT_JNLP_IMAGE);
    }
    Map<String, EnvVar> envVars = defaultEnvVars(slave,
            jnlp.getWorkingDir() != null ? jnlp.getWorkingDir() : ContainerTemplate.DEFAULT_WORKING_DIR,
            template.getEnvVars());
    envVars.putAll(jnlp.getEnv().stream().collect(Collectors.toMap(EnvVar::getName, Function.identity())));
    jnlp.setEnv(new ArrayList<>(envVars.values()));

    // default workspace volume, add an empty volume to share the workspace across the pod
    if (pod.getSpec().getVolumes().stream().noneMatch(v -> WORKSPACE_VOLUME_NAME.equals(v.getName()))) {
        pod.getSpec().getVolumes().add(
                new VolumeBuilder().withName(WORKSPACE_VOLUME_NAME).withNewEmptyDir().endEmptyDir().build());
    }
    // default workspace volume mount. If something is already mounted in the same path ignore it
    pod.getSpec().getContainers().stream().filter(c -> c.getVolumeMounts().stream()
            .noneMatch(vm -> vm.getMountPath().equals(
                    c.getWorkingDir() != null ? c.getWorkingDir() : ContainerTemplate.DEFAULT_WORKING_DIR)))
            .forEach(c -> c.getVolumeMounts().add(getDefaultVolumeMount(c.getWorkingDir())));

    LOGGER.log(Level.FINE, "Pod built: {0}", pod);
    return pod;
}

From source file:io.soabase.halva.processor.caseclass.Templates.java

void addTuple(CaseClassSpec spec, TypeSpec.Builder builder) {
    Optional<Class<? extends Tuple>> optionalTupleClass = Tuple.getTupleClass(spec.getItems().size());
    boolean hasThisTuple = optionalTupleClass.isPresent();
    Class<? extends Tuple> tupleClass = optionalTupleClass.orElse(Tuple.class);

    TypeName typeName;//from w w  w .  j  a  v  a  2  s . co m
    CodeBlock codeBlock;
    if (hasThisTuple) {
        List<TypeName> typeNameList = spec.getItems().stream()
                .map(item -> environment.getGeneratedManager().toTypeName(item.getType()).box())
                .collect(Collectors.toList());
        typeName = getTupleType(tupleClass, typeNameList);

        String args = spec.getItems().stream().map(item -> item.getName() + "()")
                .collect(Collectors.joining(", "));

        codeBlock = CodeBlock.builder().addStatement("return $T.Tu($L)", Tuple.class, args).build();
    } else {
        typeName = ClassName.get(tupleClass);

        codeBlock = CodeBlock.builder().addStatement("throw new $T($S)", UnsupportedOperationException.class,
                "Too many arguments for a Tuple").build();
    }

    MethodSpec methodSpec = MethodSpec.methodBuilder("tuple").returns(typeName).addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC).addCode(codeBlock).build();
    builder.addMethod(methodSpec);
}

From source file:org.apache.tinkerpop.gremlin.neo4j.structure.Neo4jGraph.java

private void initialize(final Neo4jGraphAPI baseGraph, final Configuration configuration) {
    this.configuration.copy(configuration);
    this.baseGraph = baseGraph;
    this.neo4jGraphVariables = new Neo4jGraphVariables(this);
    this.tx().readWrite();
    final Optional<Boolean> hasMultiProperties = this.neo4jGraphVariables
            .get(Graph.Hidden.hide(CONFIG_MULTI_PROPERTIES));
    final Optional<Boolean> hasMetaProperties = this.neo4jGraphVariables
            .get(Graph.Hidden.hide(CONFIG_META_PROPERTIES));
    boolean supportsMetaProperties = hasMetaProperties
            .orElse(this.configuration.getBoolean(CONFIG_META_PROPERTIES, false));
    boolean supportsMultiProperties = hasMultiProperties
            .orElse(this.configuration.getBoolean(CONFIG_MULTI_PROPERTIES, false));
    if (supportsMultiProperties != supportsMetaProperties)
        throw new IllegalArgumentException(this.getClass().getSimpleName()
                + " currently supports either both meta-properties and multi-properties or neither");
    if (!hasMultiProperties.isPresent())
        this.neo4jGraphVariables.set(Graph.Hidden.hide(CONFIG_MULTI_PROPERTIES), supportsMultiProperties);
    if (!hasMetaProperties.isPresent())
        this.neo4jGraphVariables.set(Graph.Hidden.hide(CONFIG_META_PROPERTIES), supportsMetaProperties);
    this.trait = supportsMultiProperties ? MultiMetaNeo4jTrait.instance() : NoMultiNoMetaNeo4jTrait.instance();
    if (supportsMultiProperties)
        LOGGER.warn(this.getClass().getSimpleName()
                + " multi/meta-properties feature is considered experimental and should not be used in a production setting until this warning is removed");
    this.tx().commit();
}