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:com.ikanow.aleph2.analytics.services.AnalyticsContext.java

/** Returns a config object containing:
 *  - set up for any of the services described
 *  - all the rest of the configuration/*www . j av a2s . co m*/
 *  - the bucket bean ID
 *  SIDE EFFECT - SETS UP THE SERVICES SET 
 * @param services
 * @return
 */
protected Config setupServices(final Optional<DataBucketBean> maybe_bucket,
        final Optional<Set<Tuple2<Class<? extends IUnderlyingService>, Optional<String>>>> services) {
    // 
    // - set up for any of the services described
    // - all the rest of the configuration
    // - the bucket bean ID

    final Config full_config = ModuleUtils.getStaticConfig()
            .withoutPath(DistributedServicesPropertyBean.APPLICATION_NAME)
            .withoutPath("MongoDbManagementDbService.v1_enabled") // (special workaround for V1 sync service)
    ;

    final ImmutableSet<Tuple2<Class<? extends IUnderlyingService>, Optional<String>>> complete_services_set = ImmutableSet
            .<Tuple2<Class<? extends IUnderlyingService>, Optional<String>>>builder()
            .addAll(services.orElse(Collections.emptySet()))
            .add(Tuples._2T(ICoreDistributedServices.class, Optional.empty()))
            .add(Tuples._2T(IManagementDbService.class, Optional.empty()))
            .add(Tuples._2T(ISearchIndexService.class, Optional.empty())) //(need this because logging doesn't correctly report its service set, should fix at some point)
            .add(Tuples._2T(IStorageService.class, Optional.empty()))
            .add(Tuples._2T(ISecurityService.class, Optional.empty()))
            .add(Tuples._2T(ILoggingService.class, Optional.empty()))
            .add(Tuples._2T(IManagementDbService.class, IManagementDbService.CORE_MANAGEMENT_DB))
            .addAll(_mutable_state.extra_auto_context_libs)
            .addAll(maybe_bucket
                    .map(bucket -> DataServiceUtils.listUnderlyingServiceProviders(bucket.data_schema()))
                    .orElse(Collections.emptyList()))
            .build();

    if (_mutable_state.service_manifest_override.isSet()) {
        if (!complete_services_set.equals(_mutable_state.service_manifest_override.get())) {
            throw new RuntimeException(ErrorUtils.SERVICE_RESTRICTIONS);
        }
    } else {
        _mutable_state.service_manifest_override.set(complete_services_set);
    }
    return full_config;
}

From source file:com.mweagle.tereus.commands.CreateCommand.java

protected void createStack(Optional<String> stackName, TereusInput tereusInput, JsonElement templateData,
        boolean logTemplate) throws UnsupportedEncodingException {
    if (tereusInput.dryRun) {
        tereusInput.logger.info("Dry run requested (-n/--noop). Stack creation bypassed.");
        if (logTemplate) {
            final String formattedTemplate = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping()
                    .create().toJson(templateData);
            tereusInput.logger.info("Stack Template:\n {}", formattedTemplate);
        }// w  ww . j  a  v  a2s.  c om
    } else {
        final String bucketName = tereusInput.params.get(CONSTANTS.PARAMETER_NAMES.S3_BUCKET_NAME).toString();
        // Upload the template
        final String templateContent = new GsonBuilder().create().toJson(templateData);
        final byte[] templateBytes = templateContent.getBytes("UTF-8");
        final InputStream is = new ByteArrayInputStream(templateBytes);
        final String templateDigest = DigestUtils.sha256Hex(templateBytes);
        final String keyName = String.format("%s-tereus.cf.template", templateDigest);

        try (S3Resource resource = new S3Resource(bucketName, keyName, is,
                Optional.of(Long.valueOf(templateBytes.length)))) {
            resource.upload();
            final EstimateTemplateCostRequest costRequest = new EstimateTemplateCostRequest();
            costRequest.setParameters(toParameterList(tereusInput.params));
            costRequest.setTemplateURL(resource.getResourceURL().get());
            final AmazonCloudFormationClient awsClient = new AmazonCloudFormationClient(
                    tereusInput.awsCredentials);
            awsClient.setRegion(tereusInput.awsRegion);
            final EstimateTemplateCostResult costResult = awsClient.estimateTemplateCost(costRequest);
            tereusInput.logger.info("Cost Estimator: {}", costResult.getUrl());

            // Go ahead and create the stack.
            final String defaultTemplateName = String.format("Tereus-%s", System.currentTimeMillis());
            final CreateStackRequest request = new CreateStackRequest()
                    .withStackName(stackName.orElse(defaultTemplateName))
                    .withTemplateURL(resource.getResourceURL().get())
                    .withParameters(toParameterList(tereusInput.params)).withTags(toTagList(tereusInput.tags))
                    .withCapabilities("CAPABILITY_IAM");
            tereusInput.logger.debug("Creating stack: {}", stackName);
            tereusInput.logger.debug("Stack params: {}", request.getParameters());
            tereusInput.logger.debug("Stack tags: {}", request.getTags());
            final Optional<DescribeStacksResult> result = new CloudFormation().createStack(request,
                    tereusInput.awsRegion, tereusInput.logger);
            if (result.isPresent()) {
                tereusInput.logger.info("Stack successfully created");
                tereusInput.logger.info(result.get().toString());
                resource.setReleased(true);
            }
        }
    }
}

From source file:org.flowable.engine.impl.dynamic.AbstractDynamicStateManager.java

protected void prepareMoveExecutionEntityContainer(MoveExecutionEntityContainer moveExecutionContainer,
        Optional<String> migrateToProcessDefinitionId, CommandContext commandContext) {
    ExpressionManager expressionManager = CommandContextUtil.getProcessEngineConfiguration(commandContext)
            .getExpressionManager();/* w w w .j  a  v a  2  s  .c  o  m*/

    Optional<BpmnModel> bpmnModelToMigrateTo = migrateToProcessDefinitionId
            .map(ProcessDefinitionUtil::getBpmnModel);
    boolean canContainerDirectMigrate = (moveExecutionContainer.getMoveToActivityIds().size() == 1)
            && (moveExecutionContainer.getExecutions().size() == 1);
    for (String activityId : moveExecutionContainer.getMoveToActivityIds()) {
        FlowElement currentFlowElement;
        FlowElement newFlowElement;
        String currentActivityId;
        if (moveExecutionContainer.isMoveToParentProcess()) {
            String parentProcessDefinitionId = moveExecutionContainer.getSuperExecution()
                    .getProcessDefinitionId();
            BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(parentProcessDefinitionId);
            BpmnModel modelOfCallActivity = ProcessDefinitionUtil
                    .getBpmnModel(moveExecutionContainer.getExecutions().get(0).getProcessDefinitionId());
            currentActivityId = moveExecutionContainer.getExecutions().get(0).getCurrentActivityId();
            currentFlowElement = resolveFlowElementFromBpmnModel(modelOfCallActivity, currentActivityId);
            newFlowElement = resolveFlowElementFromBpmnModel(bpmnModelToMigrateTo.orElse(bpmnModel),
                    activityId);
            canContainerDirectMigrate = false;
        } else if (moveExecutionContainer.isMoveToSubProcessInstance()) {
            //The subProcess model is defined in the callActivity of the current processDefinition or the migrateProcessDefinition if defined
            ExecutionEntity firstExecution = moveExecutionContainer.getExecutions().get(0);
            BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(firstExecution.getProcessDefinitionId());
            currentActivityId = firstExecution.getCurrentActivityId();
            currentFlowElement = resolveFlowElementFromBpmnModel(bpmnModel, currentActivityId);

            String processDefinitionIdOfCallActivity = migrateToProcessDefinitionId
                    .orElse(firstExecution.getProcessDefinitionId());
            CallActivity callActivity = (CallActivity) resolveFlowElementFromBpmnModel(
                    bpmnModelToMigrateTo.orElse(bpmnModel), moveExecutionContainer.getCallActivityId());

            moveExecutionContainer.setCallActivity(callActivity);
            ProcessDefinition callActivityProcessDefinition = ProcessDefinitionUtil
                    .getProcessDefinition(processDefinitionIdOfCallActivity);
            String tenantId = callActivityProcessDefinition.getTenantId();
            Integer calledProcessVersion = moveExecutionContainer.getCallActivitySubProcessVersion();
            String calledProcessDefKey = callActivity.getCalledElement();
            if (isExpression(calledProcessDefKey)) {
                try {
                    calledProcessDefKey = expressionManager.createExpression(calledProcessDefKey)
                            .getValue(firstExecution.getProcessInstance()).toString();
                } catch (FlowableException e) {
                    throw new FlowableException("Cannot resolve calledElement expression '"
                            + calledProcessDefKey + "' of callActivity '" + callActivity.getId() + "'", e);
                }
            }
            moveExecutionContainer.setSubProcessDefKey(calledProcessDefKey);
            ProcessDefinition subProcessDefinition = resolveProcessDefinition(calledProcessDefKey,
                    calledProcessVersion, tenantId, commandContext);
            BpmnModel subProcessModel = ProcessDefinitionUtil.getBpmnModel(subProcessDefinition.getId());
            moveExecutionContainer.setSubProcessDefinition(subProcessDefinition);
            moveExecutionContainer.setSubProcessModel(subProcessModel);

            newFlowElement = resolveFlowElementFromBpmnModel(subProcessModel, activityId);
            canContainerDirectMigrate = false;
        } else {
            // Get first execution to get process definition id
            ExecutionEntity firstExecution = moveExecutionContainer.getExecutions().get(0);
            BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(firstExecution.getProcessDefinitionId());
            currentActivityId = firstExecution.getCurrentActivityId();
            currentFlowElement = resolveFlowElementFromBpmnModel(bpmnModel, currentActivityId);
            newFlowElement = resolveFlowElementFromBpmnModel(bpmnModelToMigrateTo.orElse(bpmnModel),
                    activityId);
        }

        moveExecutionContainer.addMoveToFlowElement(activityId, currentFlowElement, newFlowElement);
        canContainerDirectMigrate = canContainerDirectMigrate
                && isDirectFlowElementExecutionMigration(currentFlowElement, newFlowElement);
    }

    moveExecutionContainer
            .setDirectExecutionMigration(canContainerDirectMigrate && migrateToProcessDefinitionId.isPresent());
}

From source file:net.sf.jabref.external.DroppedFileHandler.java

/**
 * Make a extension to the file.//from   w  w  w.ja va 2s.  co  m
 *
 * @param entry    The entry to extension from.
 * @param fileType The FileType associated with the file.
 * @param filename The path to the file.
 * @param edits    An NamedCompound action this action is to be added to. If none
 *                 is given, the edit is added to the panel's undoManager.
 */
private void doLink(BibEntry entry, ExternalFileType fileType, String filename, boolean avoidDuplicate,
        NamedCompound edits) {

    Optional<String> oldValue = entry.getFieldOptional(FieldName.FILE);
    FileListTableModel tm = new FileListTableModel();
    oldValue.ifPresent(tm::setContent);

    // If avoidDuplicate==true, we should check if this file is already linked:
    if (avoidDuplicate) {
        // For comparison, find the absolute filename:
        List<String> dirs = panel.getBibDatabaseContext().getFileDirectory();
        String absFilename;
        if (new File(filename).isAbsolute() || dirs.isEmpty()) {
            absFilename = filename;
        } else {
            Optional<File> file = FileUtil.expandFilename(filename, dirs);
            if (file.isPresent()) {
                absFilename = file.get().getAbsolutePath();
            } else {
                absFilename = ""; // This shouldn't happen based on the old code, so maybe one should set it something else?
            }
        }

        LOGGER.debug("absFilename: " + absFilename);

        for (int i = 0; i < tm.getRowCount(); i++) {
            FileListEntry flEntry = tm.getEntry(i);
            // Find the absolute filename for this existing link:
            String absName;
            if (new File(flEntry.link).isAbsolute() || dirs.isEmpty()) {
                absName = flEntry.link;
            } else {
                Optional<File> file = FileUtil.expandFilename(flEntry.link, dirs);
                if (file.isPresent()) {
                    absName = file.get().getAbsolutePath();
                } else {
                    absName = null;
                }
            }
            LOGGER.debug("absName: " + absName);
            // If the filenames are equal, we don't need to link, so we simply return:
            if (absFilename.equals(absName)) {
                return;
            }
        }
    }

    tm.addEntry(tm.getRowCount(), new FileListEntry("", filename, fileType));
    String newValue = tm.getStringRepresentation();
    UndoableFieldChange edit = new UndoableFieldChange(entry, FieldName.FILE, oldValue.orElse(null), newValue);
    entry.setField(FieldName.FILE, newValue);

    if (edits == null) {
        panel.getUndoManager().addEdit(edit);
    } else {
        edits.addEdit(edit);
    }
}

From source file:com.hortonworks.streamline.streams.catalog.service.StreamCatalogService.java

public Topology cloneTopology(Long namespaceId, Topology topology) throws Exception {
    Preconditions.checkNotNull(topology, "Topology does not exist");
    TopologyData exported = new TopologyData(doExportTopology(topology));
    Optional<String> latest = getLatestCloneName(exported.getTopologyName(), listTopologies());
    exported.setTopologyName(getNextCloneName(latest.orElse(topology.getName())));
    if (namespaceId == null) {
        namespaceId = topology.getNamespaceId();
    }/* w w  w . j a  va 2 s .  co m*/
    return importTopology(namespaceId, exported);
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Examine the {@linkplain HttpResponse#getStatusLine() status} {@link StatusLine#getStatusCode() code} from the
 * response to the {@linkplain #doProxyRequest(Page.Request, Channel.Mode) proxy request} and throw an exception if
 * something went wrong./*from   ww w.j a v a  2 s. c om*/
 * 
 * @param proxyContext The {@link HttpClientContext} containing the {@linkplain ExecutionContext#HTTP_RESPONSE
 * response} from the proxied server.
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @return The supplied <code>proxyClientContext</code> argument.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #doProxyRequest(Page.Request, Channel.Mode)
 */
protected HttpClientContext validateProxyResponse(final HttpClientContext proxyContext,
        final Page.Request pageRequest, final Mode mode)
        throws WWWEEEPortal.Exception, WebApplicationException {
    final HttpResponse proxyResponse = proxyContext.getResponse();
    final int responseCode = proxyResponse.getStatusLine().getStatusCode();
    if (responseCode == Response.Status.OK.getStatusCode())
        return proxyContext;
    try {
        if (responseCode == Response.Status.NOT_MODIFIED.getStatusCode()) {
            throw new WebApplicationException(Response.Status.NOT_MODIFIED);
        } else if (((responseCode >= Response.Status.MOVED_PERMANENTLY.getStatusCode())
                && (responseCode <= Response.Status.SEE_OTHER.getStatusCode()))
                || (responseCode == Response.Status.TEMPORARY_REDIRECT.getStatusCode())) { // Moved Permanently, Found, See Other, Temporary Redirect
            if (pageRequest.isMaximized(this)) {
                final URI fixedLocation;
                try {
                    final Optional<URI> locationURI = HttpUtil.getValue(proxyResponse.getLastHeader("Location"),
                            URI::create);
                    final URL proxiedFileURL = HttpUtil.getRequestTargetURL(proxyContext);
                    fixedLocation = rewriteProxiedFileLink(pageRequest, proxiedFileURL,
                            locationURI.orElse(null), Mode.VIEW.equals(mode), true).getKey();
                } catch (Exception e) {
                    throw new ContentManager.ContentException("Error rewriting 'Location' header", e);
                }
                throw new WebApplicationException(
                        Response.status(RESTUtil.Response.Status.fromStatusCode(responseCode))
                                .location(fixedLocation).build());
            }
        } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
            if (pageRequest.isMaximized(this)) {
                throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED)
                        .header("WWW-Authenticate", HttpUtil
                                .getValue(proxyResponse.getLastHeader("WWW-Authenticate"), Function.identity())
                                .orElse(null))
                        .build());
            }
        } else if ((responseCode == Response.Status.NOT_FOUND.getStatusCode())
                || (responseCode == Response.Status.GONE.getStatusCode())) {
            final URI channelLocalPath = pageRequest.getChannelLocalPath(this);
            if (channelLocalPath != null) {
                throw new WebApplicationException(Response.Status.fromStatusCode(responseCode));
            }
        } else if (responseCode == RESTUtil.Response.Status.METHOD_NOT_ALLOWED.getStatusCode()) {
            final URI channelLocalPath = pageRequest.getChannelLocalPath(this);
            if (channelLocalPath != null) {
                throw new WebApplicationException(
                        Response.status(RESTUtil.Response.Status.METHOD_NOT_ALLOWED)
                                .header("Allow", HttpUtil
                                        .getValue(proxyResponse.getLastHeader("Allow"), Function.identity())
                                        .orElse(null))
                                .build());
            }
        } else if (responseCode == RESTUtil.Response.Status.REQUEST_TIMEOUT.getStatusCode()) { // we didn't send it to the proxied server fast enough!?
            throw new WWWEEEPortal.OperationalException(new WebApplicationException(responseCode));
        } else if (responseCode == Response.Status.BAD_REQUEST.getStatusCode()) {
            throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).build());
        } else if ((responseCode >= 400) && (responseCode < 500)) { // All other 4XX errors
            if (pageRequest.isMaximized(this)) {
                throw new WebApplicationException(
                        Response.status(RESTUtil.Response.Status.fromStatusCode(responseCode)).build());
            }
        } else if ((responseCode >= RESTUtil.Response.Status.BAD_GATEWAY.getStatusCode())
                && (responseCode <= RESTUtil.Response.Status.GATEWAY_TIMEOUT.getStatusCode())) { // Bad Gateway, Service Unavailable, Gateway Timeout
            throw new WWWEEEPortal.OperationalException(new WebApplicationException(responseCode));
        }
        final Response.StatusType statusType = RESTUtil.Response.Status.fromStatusCode(responseCode);
        final String codePhrase = (statusType != null) ? " (" + statusType.getReasonPhrase() + ")" : "";
        final String responsePhrase = (proxyResponse.getStatusLine().getReasonPhrase() != null)
                ? ": " + proxyResponse.getStatusLine().getReasonPhrase()
                : "";
        final ConfigManager.ConfigException configurationException = new ConfigManager.ConfigException(
                "The proxied file server returned code '" + responseCode + "'" + codePhrase + responsePhrase,
                null);
        if (getLogger().isLoggable(Level.FINE)) {
            try {
                final Reader reader = createProxiedFileReader(proxyResponse, getProxyResponseHeader(pageRequest,
                        proxyResponse, "Content-Type", IOUtil::newMimeType));
                LogAnnotation.annotate(configurationException, "ProxiedFileResponseContent",
                        (reader != null) ? IOUtil.toString(reader) : null, Level.FINE, false);
            } catch (Exception e) {
            }
        }
        throw configurationException;
    } catch (WWWEEEPortal.Exception wpe) {
        try {
            LogAnnotation.annotate(wpe, "ProxiedFileURL", HttpUtil.getRequestTargetURL(proxyContext), null,
                    false);
        } catch (Exception e) {
        }
        LogAnnotation.annotate(wpe, "ProxiedFileResponseCode", responseCode, null, false);
        LogAnnotation.annotate(wpe, "ProxiedFileResponseCodeReasonPhrase",
                RESTUtil.Response.Status.fromStatusCode(responseCode), null, false);
        LogAnnotation.annotate(wpe, "ProxiedFileResponseReasonPhrase",
                proxyResponse.getStatusLine().getReasonPhrase(), null, false);
        throw wpe;
    }
}

From source file:org.trellisldp.http.impl.PostHandler.java

/**
 * Create a new resource/*ww  w  . j a va 2 s.c om*/
 * @return the response builder
 */
public ResponseBuilder createResource() {
    final String baseUrl = getBaseUrl();
    final String identifier = baseUrl + req.getPartition() + req.getPath() + id;
    final String contentType = req.getContentType();
    final Session session = ofNullable(req.getSession()).orElseGet(HttpSession::new);

    LOGGER.info("Creating resource as {}", identifier);

    final Optional<RDFSyntax> rdfSyntax = ofNullable(contentType).flatMap(RDFSyntax::byMediaType)
            .filter(SUPPORTED_RDF_TYPES::contains);

    final IRI defaultType = nonNull(contentType) && !rdfSyntax.isPresent() ? LDP.NonRDFSource : LDP.RDFSource;
    final IRI internalId = rdf.createIRI(TRELLIS_PREFIX + req.getPartition() + req.getPath() + id);

    // Add LDP type (ldp:Resource results in the defaultType)
    final IRI ldpType = ofNullable(req.getLink()).filter(l -> "type".equals(l.getRel())).map(Link::getUri)
            .map(URI::toString).filter(l -> l.startsWith(LDP.URI)).map(rdf::createIRI)
            .filter(l -> !LDP.Resource.equals(l)).orElse(defaultType);

    if (ldpType.equals(LDP.NonRDFSource) && rdfSyntax.isPresent()) {
        return status(BAD_REQUEST).type(TEXT_PLAIN).entity("Cannot save a NonRDFSource with RDF syntax");
    }

    try (final TrellisDataset dataset = TrellisDataset.createDataset()) {

        // Add Audit quads
        audit.ifPresent(svc -> svc.creation(internalId, session).stream()
                .map(skolemizeQuads(resourceService, baseUrl)).forEachOrdered(dataset::add));

        dataset.add(rdf.createQuad(PreferServerManaged, internalId, RDF.type, ldpType));

        // Add user-supplied data
        if (ldpType.equals(LDP.NonRDFSource)) {
            // Check the expected digest value
            final Digest digest = req.getDigest();
            if (nonNull(digest) && !getDigestForEntity(digest).equals(digest.getDigest())) {
                return status(BAD_REQUEST);
            }

            final Map<String, String> metadata = singletonMap(CONTENT_TYPE,
                    ofNullable(contentType).orElse(APPLICATION_OCTET_STREAM));
            final IRI binaryLocation = rdf
                    .createIRI(binaryService.getIdentifierSupplier(req.getPartition()).get());
            dataset.add(rdf.createQuad(PreferServerManaged, internalId, DC.hasPart, binaryLocation));
            dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.modified,
                    rdf.createLiteral(now().toString(), XSD.dateTime)));
            dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.format,
                    rdf.createLiteral(ofNullable(contentType).orElse(APPLICATION_OCTET_STREAM))));
            dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.extent,
                    rdf.createLiteral(Long.toString(entity.length()), XSD.long_)));

            // Persist the content
            persistContent(binaryLocation, metadata);
        } else {
            readEntityIntoDataset(identifier, baseUrl, PreferUserManaged, rdfSyntax.orElse(TURTLE), dataset);

            // Check for any constraints
            checkConstraint(dataset, PreferUserManaged, ldpType, TRELLIS_PREFIX + req.getPartition(),
                    rdfSyntax.orElse(TURTLE));
        }

        if (resourceService.put(internalId, dataset.asDataset())) {
            final ResponseBuilder builder = status(CREATED).location(create(identifier));

            // Add LDP types
            ldpResourceTypes(ldpType).map(IRI::getIRIString).forEach(type -> builder.link(type, "type"));

            return builder;
        }
    }

    LOGGER.error("Unable to persist data to location at {}", internalId.getIRIString());
    return serverError().type(TEXT_PLAIN)
            .entity("Unable to persist data. Please consult the logs for more information");
}

From source file:io.swagger.v3.parser.util.OpenAPIDeserializer.java

public SecurityScheme getSecurityScheme(ObjectNode node, String location, ParseResult result) {
    if (node == null) {
        return null;
    }//w ww.ja  v a2s  . co m

    SecurityScheme securityScheme = new SecurityScheme();

    JsonNode ref = node.get("$ref");
    if (ref != null) {
        if (ref.getNodeType().equals(JsonNodeType.STRING)) {
            String mungedRef = mungedRef(ref.textValue());
            if (mungedRef != null) {
                securityScheme.set$ref(mungedRef);
            } else {
                securityScheme.set$ref(ref.textValue());
            }
            return securityScheme;
        } else {
            result.invalidType(location, "$ref", "string", node);
            return null;
        }
    }

    boolean descriptionRequired, bearerFormatRequired, nameRequired, inRequired, schemeRequired, flowsRequired,
            openIdConnectRequired;
    descriptionRequired = bearerFormatRequired = nameRequired = inRequired = schemeRequired = flowsRequired = openIdConnectRequired = false;

    String value = getString("type", node, true, location, result);
    if (StringUtils.isNotBlank(value)) {
        if (SecurityScheme.Type.APIKEY.toString().equals(value)) {
            securityScheme.setType(SecurityScheme.Type.APIKEY);
            nameRequired = inRequired = true;
        } else if (SecurityScheme.Type.HTTP.toString().equals(value)) {
            securityScheme.setType(SecurityScheme.Type.HTTP);
            schemeRequired = true;
        } else if (SecurityScheme.Type.OAUTH2.toString().equals(value)) {
            securityScheme.setType(SecurityScheme.Type.OAUTH2);
            flowsRequired = true;
        } else if (SecurityScheme.Type.OPENIDCONNECT.toString().equals(value)) {
            securityScheme.setType(SecurityScheme.Type.OPENIDCONNECT);
            openIdConnectRequired = true;
        } else {
            result.invalidType(location + ".type", "type", "http|apiKey|oauth2|openIdConnect ", node);
        }
    }
    value = getString("description", node, descriptionRequired, location, result);
    if (StringUtils.isNotBlank(value)) {
        securityScheme.setDescription(value);
    }

    value = getString("name", node, nameRequired, location, result);
    if (StringUtils.isNotBlank(value)) {
        securityScheme.setName(value);
    }

    final String securitySchemeIn = getString("in", node, inRequired, location, result);
    final Optional<SecurityScheme.In> matchingIn = Arrays.stream(SecurityScheme.In.values())
            .filter(in -> in.toString().equals(securitySchemeIn)).findFirst();

    securityScheme.setIn(matchingIn.orElse(null));

    value = getString("scheme", node, schemeRequired, location, result);
    if (StringUtils.isNotBlank(value)) {
        securityScheme.setScheme(value);
    }

    value = getString("bearerFormat", node, bearerFormatRequired, location, result);
    if (StringUtils.isNotBlank(value)) {
        securityScheme.setBearerFormat(value);
    }

    ObjectNode flowsObject = getObject("flows", node, flowsRequired, location, result);
    if (flowsObject != null) {
        securityScheme.setFlows(getOAuthFlows(flowsObject, location, result));
    }

    value = getString("openIdConnectUrl", node, openIdConnectRequired, location, result);
    if (StringUtils.isNotBlank(value)) {
        securityScheme.setOpenIdConnectUrl(value);
    }

    Map<String, Object> extensions = getExtensions(node);
    if (extensions != null && extensions.size() > 0) {
        securityScheme.setExtensions(extensions);
    }

    Set<String> securitySchemeKeys = getKeys(node);
    for (String key : securitySchemeKeys) {
        if (!SECURITY_SCHEME_KEYS.contains(key) && !key.startsWith("x-")) {
            result.extra(location, key, node.get(key));
        }
    }

    return securityScheme;
}

From source file:com.ikanow.aleph2.analytics.services.AnalyticsContext.java

/** Gets the secondary buffer (deletes any existing data, and switches to "ping" on an uninitialized index)
 *  NOTE: CAN HAVE SIDE EFFECTS IF UNINITIALIZED
 * @param bucket/*from  w w  w . ja v  a  2s.co  m*/
 * @param job - if present _and_ points to transient output, then returns the buffers for that transient output, else for the entire bucket
 * @param need_ping_pong_buffer - based on the job.output
 * @param data_service
 * @return
 */
protected Optional<String> getSecondaryBuffer(final DataBucketBean bucket,
        final Optional<AnalyticThreadJobBean> job, final boolean need_ping_pong_buffer,
        final IGenericDataService data_service) {
    if (need_ping_pong_buffer) {
        final Optional<String> job_name = job
                .filter(j -> Optionals.of(() -> j.output().is_transient()).orElse(false)).map(j -> j.name());
        final Optional<String> write_buffer = data_service.getPrimaryBufferName(bucket, job_name)
                .map(Optional::of).orElseGet(() -> { // Two cases:

                    final Set<String> secondaries = data_service.getSecondaryBuffers(bucket, job_name);
                    final int ping_pong_count = (secondaries.contains(IGenericDataService.SECONDARY_PING) ? 1
                            : 0) + (secondaries.contains(IGenericDataService.SECONDARY_PONG) ? 1 : 0);

                    if (1 == ping_pong_count) { // 1) one of ping/pong exists but not the other ... this is the file case where we can't tell what the primary actually is
                        if (secondaries.contains(IGenericDataService.SECONDARY_PONG)) { //(eg pong is secondary so ping must be primary)
                            return Optional.of(IGenericDataService.SECONDARY_PING);
                        } else
                            return Optional.of(IGenericDataService.SECONDARY_PONG);
                    } else { // 2) all other cases: this is the ES case, where we just use an alias to switch ..
                        // So here there are side effects
                        if (_state_name == State.IN_MODULE) { // this should not happen (unless the data service doesn't support secondary buffers)
                            _logger.warn(ErrorUtils.get(
                                    "Startup case: no primary buffer for bucket:job {0}:{1} service {2}, number of secondary buffers = {3} (ping/pong={4}, secondaries={5})",
                                    bucket.full_name(), job_name.orElse("(none)"),
                                    data_service.getClass().getSimpleName(), ping_pong_count,
                                    need_ping_pong_buffer,
                                    secondaries.stream().collect(Collectors.joining(";"))));
                        } else {
                            _logger.info(ErrorUtils.get(
                                    "Startup case: no primary buffer for bucket:job {0}:{1} service {2}, number of secondary buffers = {3} (ping/pong={4})",
                                    bucket.full_name(), job_name.orElse("(none)"),
                                    data_service.getClass().getSimpleName(), ping_pong_count,
                                    need_ping_pong_buffer));
                        }

                        // ... but we don't currently have a primary so need to build that
                        if (0 == ping_pong_count) { // first time through, create the buffers:
                            data_service.getWritableDataService(JsonNode.class, bucket, Optional.empty(),
                                    Optional.of(IGenericDataService.SECONDARY_PONG));
                            data_service.getWritableDataService(JsonNode.class, bucket, Optional.empty(),
                                    Optional.of(IGenericDataService.SECONDARY_PING));
                        }
                        final Optional<String> curr_primary = Optional.of(IGenericDataService.SECONDARY_PING);
                        final CompletableFuture<BasicMessageBean> future_res = data_service
                                .switchCrudServiceToPrimaryBuffer(bucket, curr_primary, Optional.empty(),
                                        job_name);
                        future_res.thenAccept(res -> {
                            if (!res.success()) {
                                _logger.warn(ErrorUtils.get(
                                        "Error switching between ping/pong buffers (service {0}: ",
                                        data_service.getClass().getSimpleName()) + res.message());
                            }
                        });
                        return curr_primary;
                    }
                }).map(curr_pri -> { // then just pick the buffer that isn't the primary
                    if (IGenericDataService.SECONDARY_PING.equals(curr_pri)) {
                        return IGenericDataService.SECONDARY_PONG;
                    } else
                        return IGenericDataService.SECONDARY_PING;
                });

        return write_buffer;
    } else
        return Optional.empty();
}

From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java

private CompletableFuture<Boolean> isTableAvailable(TableName tableName, Optional<byte[][]> splitKeys) {
    if (TableName.isMetaTableName(tableName)) {
        return connection.registry.getMetaRegionLocation().thenApply(locs -> Stream
                .of(locs.getRegionLocations()).allMatch(loc -> loc != null && loc.getServerName() != null));
    }/*from   w  ww  .j a  v a 2s .c o m*/
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    addListener(isTableEnabled(tableName), (enabled, error) -> {
        if (error != null) {
            if (error instanceof TableNotFoundException) {
                future.complete(false);
            } else {
                future.completeExceptionally(error);
            }
            return;
        }
        if (!enabled) {
            future.complete(false);
        } else {
            addListener(AsyncMetaTableAccessor.getTableHRegionLocations(metaTable, Optional.of(tableName)),
                    (locations, error1) -> {
                        if (error1 != null) {
                            future.completeExceptionally(error1);
                            return;
                        }
                        List<HRegionLocation> notDeployedRegions = locations.stream()
                                .filter(loc -> loc.getServerName() == null).collect(Collectors.toList());
                        if (notDeployedRegions.size() > 0) {
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Table " + tableName + " has " + notDeployedRegions.size()
                                        + " regions");
                            }
                            future.complete(false);
                            return;
                        }

                        Optional<Boolean> available = splitKeys
                                .map(keys -> compareRegionsWithSplitKeys(locations, keys));
                        future.complete(available.orElse(true));
                    });
        }
    });
    return future;
}