Example usage for java.util Optional isPresent

List of usage examples for java.util Optional isPresent

Introduction

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

Prototype

public boolean isPresent() 

Source Link

Document

If a value is present, returns true , otherwise false .

Usage

From source file:br.com.blackhubos.eventozero.updater.assets.uploader.Uploader.java

@SuppressWarnings("unchecked")
public static Optional<Uploader> parseJsonObject(JSONObject parse, MultiTypeFormatter formatter) {

    long id = Long.MIN_VALUE;
    String name = null;/*from   w  w w.j  a v a 2 s  .co  m*/
    boolean admin = false;
    // Loop em todas entradas do JSON
    for (Map.Entry entries : (Set<Map.Entry>) parse.entrySet()) {

        Object key = entries.getKey();
        Object value = entries.getValue();
        String valueString = String.valueOf(value);
        /** Transforma o objeto em um {@link AssetUploaderInput) para usar com switch **/
        switch (AssetUploaderInput.parseObject(key)) {
        case ADMIN: {
            // Obtem o valor que indica se quem enviou era administrador
            if (formatter.canFormat(Boolean.class)) {
                Optional<Boolean> result = formatter.format(value, Boolean.class);
                if (result.isPresent())
                    admin = result.get();
            }
            break;
        }
        case ID: {
            // Obtm o ID do usurio
            id = Long.parseLong(valueString);
            break;
        }
        case LOGIN: {
            // Obtm o nome/login do usurio
            name = valueString;
            break;
        }

        default: {
            break;
        }
        }
    }
    if (id == Long.MIN_VALUE || name == null) {
        return Optional.empty();
    }
    return Optional.of(new Uploader(name, admin, id));
}

From source file:org.apache.metron.elasticsearch.client.ElasticsearchClientFactory.java

private static CredentialsProvider getCredentialsProvider(ElasticsearchClientConfig esClientConfig) {
    Optional<Entry<String, String>> credentials = esClientConfig.getCredentials();
    if (credentials.isPresent()) {
        LOG.info("Found auth credentials - setting up user/pass authenticated client connection for ES.");
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials upcredentials = new UsernamePasswordCredentials(credentials.get().getKey(),
                credentials.get().getValue());
        credentialsProvider.setCredentials(AuthScope.ANY, upcredentials);
        return credentialsProvider;
    } else {//ww w.  java2 s. co m
        LOG.info(
                "Elasticsearch client credentials not provided. Defaulting to non-authenticated client connection.");
        return null;
    }
}

From source file:io.github.binout.jaxrs.csv.CsvSchemaFactory.java

static CsvSchema buildSchema(CsvMapper mapper, Class csvClass) {
    CsvAnnotationIntrospector introspector = new CsvAnnotationIntrospector(csvClass);
    char separatorChar = introspector.separator();
    Optional<String[]> columns = introspector.columns();

    CsvSchema csvSchema = mapper.schemaFor(csvClass).withColumnSeparator(separatorChar)
            .withSkipFirstDataRow(introspector.skipFirstDataRow());
    if (columns.isPresent()) {
        // Rebuild columns to take account of order
        CsvSchema.Builder builder = csvSchema.rebuild().clearColumns();
        for (String column : columns.get()) {
            CsvSchema.Column oldColumn = csvSchema.column(column);
            builder.addColumn(column, oldColumn.getType());
        }/* www.j  a v  a  2s  .  co m*/
        csvSchema = builder.build();
    }

    return csvSchema;
}

From source file:com.act.biointerpretation.sarinference.ProductScorer.java

/**
 * Reads in scored SARs, checks them against a prediction corpus and positive inchi list to get a product ranking.
 * This method is static because it does not rely on any properties of the enclosing class to construct the job.
 * TODO: It would probably make more sense to make this its own class, i.e. <ProductScorer implements JavaRunnable>
 * TODO: improve the data structure used to store scored products- using an L2PredictionCorpus is pretty ugly
 *
 * @param predictionCorpus The prediction corpus to score.
 * @param scoredSars The scored SARs to use.
 * @param lcmsFile The set of positive LCMS inchis, to use in scoring.
 * @return A JavaRunnable to run the product scoring.
 *//*from   w w  w. j  a  v  a  2s .  c  o  m*/
public static JavaRunnable getProductScorer(File predictionCorpus, File scoredSars, File lcmsFile,
        File outputFile) {

    return new JavaRunnable() {
        @Override
        public void run() throws IOException {
            // Verify files
            FileChecker.verifyInputFile(predictionCorpus);
            FileChecker.verifyInputFile(scoredSars);
            FileChecker.verifyInputFile(lcmsFile);
            FileChecker.verifyAndCreateOutputFile(outputFile);

            // Build SAR node list and best sar finder
            SarTreeNodeList nodeList = new SarTreeNodeList();
            nodeList.loadFromFile(scoredSars);
            BestSarFinder sarFinder = new BestSarFinder(nodeList);

            // Build prediction corpus
            L2PredictionCorpus predictions = L2PredictionCorpus.readPredictionsFromJsonFile(predictionCorpus);

            // Build LCMS results
            IonAnalysisInterchangeModel lcmsResults = new IonAnalysisInterchangeModel();
            lcmsResults.loadResultsFromFile(lcmsFile);

            /**
             * Build map from predictions to their scores based on SAR
             * For each prediction, we add on auxiliary info about its SARs and score to its projector name.
             * TODO: build data structure to store a scored prediction, instead of hijacking the projector name.
             */
            Map<L2Prediction, Double> predictionToScoreMap = new HashMap<>();
            LOGGER.info("Scoring predictions.");
            for (L2Prediction prediction : predictions.getCorpus()) {
                String nameAppendage = lcmsResults.getLcmsDataForPrediction(prediction).toString(); // Always tack LCMS result onto name

                Optional<SarTreeNode> maybeBestSar = sarFinder.apply(prediction);

                if (maybeBestSar.isPresent()) {
                    // If a SAR was matched, add info about it to the projector name, and put its score into the map
                    SarTreeNode bestSar = maybeBestSar.get();
                    nameAppendage += ":" + bestSar.getHierarchyId() + ":" + bestSar.getRankingScore();
                    prediction.setProjectorName(prediction.getProjectorName() + nameAppendage);
                    predictionToScoreMap.put(prediction, bestSar.getRankingScore());
                } else {
                    // If no SAR is found, append "NO_SAR" to the prediction, and give it a ranking score of 0
                    nameAppendage += "NO_SAR";
                    prediction.setProjectorName(prediction.getProjectorName() + nameAppendage);
                    predictionToScoreMap.put(prediction, 0D);
                }
            }

            LOGGER.info("Sorting predictions in decreasing order of best associated SAR rank.");
            List<L2Prediction> predictionList = new ArrayList<>(predictionToScoreMap.keySet());
            predictionList
                    .sort((a, b) -> -Double.compare(predictionToScoreMap.get(a), predictionToScoreMap.get(b)));

            // Wrap results in a corpus and write to file.
            L2PredictionCorpus finalCorpus = new L2PredictionCorpus(predictionList);
            finalCorpus.writePredictionsToJsonFile(outputFile);
            LOGGER.info("Complete!.");
        }

        @Override
        public String toString() {
            return "ProductScorer:" + scoredSars.getName();
        }
    };
}

From source file:io.github.retz.scheduler.Launcher.java

private static Protos.FrameworkInfo buildFrameworkInfo(Configuration conf) {
    String userName = conf.fileConfig.getUserName();

    Protos.FrameworkInfo.Builder fwBuilder = Protos.FrameworkInfo.newBuilder().setUser(userName)
            .setName(RetzScheduler.FRAMEWORK_NAME).setWebuiUrl(conf.fileConfig.getUri().toASCIIString())
            .setFailoverTimeout(3600 * 24 * 7).setCheckpoint(true).setPrincipal(conf.fileConfig.getPrincipal())
            .setRole(conf.fileConfig.getRole());

    Optional<String> fid = Database.getInstance().getFrameworkId();
    if (fid.isPresent()) {
        LOG.info("FrameworkID {} found", fid.get());
        fwBuilder.setId(Protos.FrameworkID.newBuilder().setValue(fid.get()).build());
    }/* w w  w.  j  a v  a  2s . c o m*/

    if (conf.fileConfig.useGPU()) {
        LOG.info("GPU enabled - registering with GPU_RESOURCES capability.");
        fwBuilder.addCapabilities(Protos.FrameworkInfo.Capability.newBuilder()
                .setType(Protos.FrameworkInfo.Capability.Type.GPU_RESOURCES).build());
    }

    LOG.info("Connecting to Mesos master {} as {}", conf.getMesosMaster(), userName);
    return fwBuilder.build();
}

From source file:gov.ca.cwds.cals.util.PlacementHomeUtil.java

private static StringBuilder composeFirstPartOfFacilityName(ApplicantDTO applicant) {
    StringBuilder sb = new StringBuilder();
    Optional<String> lastName = Optional.ofNullable(applicant.getLastName());
    Optional<String> firstName = Optional.ofNullable(applicant.getFirstName());
    lastName.ifPresent(ln -> {//from w  w w . jav a  2 s .  c om
        sb.append(ln);
        if (firstName.isPresent()) {
            sb.append(", ");
        }
    });
    firstName.ifPresent(sb::append);
    return sb;
}

From source file:io.hops.hopsworks.util.CertificateHelper.java

public static Optional<Triplet<KeyStore, KeyStore, String>> loadKeystoreFromDB(String masterPswd,
        String clusterName, ClusterCertificateFacade certFacade,
        CertificatesMgmService certificatesMgmService) {
    try {/*from  w  w  w  .j a v  a 2 s  . com*/
        Optional<ClusterCertificate> cert = certFacade.getClusterCert(clusterName);
        if (!cert.isPresent()) {
            return Optional.empty();
        }
        String certPswd = HopsUtils.decrypt(masterPswd, cert.get().getCertificatePassword(),
                certificatesMgmService.getMasterEncryptionPassword());
        KeyStore keystore, truststore;
        try (ByteArrayInputStream keystoreIS = new ByteArrayInputStream(cert.get().getClusterKey());
                ByteArrayInputStream truststoreIS = new ByteArrayInputStream(cert.get().getClusterCert())) {
            keystore = keystore(keystoreIS, certPswd);
            truststore = keystore(truststoreIS, certPswd);
        }
        return Optional.of(Triplet.with(keystore, truststore, certPswd));
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, "keystore ex. {0}", ex.getMessage());
        return Optional.empty();
    }
}

From source file:io.github.retz.scheduler.MesosHTTPFetcher.java

public static Optional<String> sandboxDownloadUri(String master, String slaveId, String frameworkId,
        String executorId, String path) {
    Optional<String> base = sandboxUri("download", master, slaveId, frameworkId, executorId);
    if (base.isPresent()) {
        try {//w w  w .jav  a2  s  . c  om
            String encodedPath = java.net.URLEncoder.encode(path,
                    java.nio.charset.StandardCharsets.UTF_8.toString());
            return Optional.of(base.get() + encodedPath);
        } catch (UnsupportedEncodingException e) {
            return Optional.empty();
        }
    }
    return Optional.empty();
}

From source file:org.openmhealth.shim.ihealth.mapper.IHealthDataPointMapper.java

/**
 * Gets the user note from a list entry node if that property exists.
 *
 * @param listEntryNode A single entry from the response result array.
 *//*  w ww. j a  va  2  s  .c  o m*/
protected static Optional<String> getUserNoteIfExists(JsonNode listEntryNode) {

    Optional<String> note = asOptionalString(listEntryNode, "Note");

    if (note.isPresent() && !note.get().isEmpty()) {

        return note;
    }

    return Optional.empty();
}

From source file:io.pravega.controller.store.stream.tables.HistoryRecord.java

public static List<Pair<Long, List<Integer>>> readAllRecords(byte[] historyTable) {
    List<Pair<Long, List<Integer>>> result = new LinkedList<>();
    Optional<HistoryRecord> record = readLatestRecord(historyTable, true);
    while (record.isPresent()) {
        result.add(new ImmutablePair<>(record.get().getScaleTime(), record.get().getSegments()));
        record = fetchPrevious(record.get(), historyTable);
    }//from  w w w  .ja  va  2 s  .c o  m
    return result;
}