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:io.pravega.controller.store.stream.tables.TableHelper.java

private static Optional<HistoryRecord> findSegmentCreatedEvent(final int startingOffset, final Segment segment,
        final byte[] historyTable) {

    Optional<HistoryRecord> historyRecordOpt = findRecordInHistoryTable(startingOffset, segment.getStart(),
            historyTable, false);//from  ww  w  .j av  a  2 s  . c o m

    if (!historyRecordOpt.isPresent()) {
        // segment not present in history record.
        return Optional.empty();
    }

    // By doing the indexed search using segment's start time we have found the record in history table that was active
    // at the time segment was created in segment table.
    // Since segment has eventTime from before scale and history record is assigned time after scale,
    // So history record's time identifying when segment was created will typically be after the segment table record.
    // This is not true for initial sets of segments though where segment.createTime == historyrecord.eventTime.
    // So we will need to check at both records. We are guaranteed that it cannot be before this though.
    // Question is should we fall thru more than one entry because of clock mismatch between controller instances.
    while (historyRecordOpt.isPresent()
            && !historyRecordOpt.get().getSegments().contains(segment.getNumber())) {
        historyRecordOpt = HistoryRecord.fetchNext(historyRecordOpt.get(), historyTable, false);
    }

    return historyRecordOpt;
}

From source file:com.ikanow.aleph2.harvest.logstash.utils.LogstashUtils.java

/** Builds a process to execute
 * @param global/*w  ww.  ja  v a  2s .c  o  m*/
 * @param bucket_config
 * @param logstash_config
 * @param requested_docs
 * @param bucket_path if this is present, will log output to /tmp/unique_sig
 * @param context 
 * @return
 */
public static ProcessBuilder buildLogstashTest(final LogstashHarvesterConfigBean global,
        final LogstashBucketConfigBean bucket_config, final String logstash_config, final long requested_docs,
        final Optional<String> bucket_path) {

    final String log_file = System.getProperty("java.io.tmpdir") + File.separator
            + BucketUtils.getUniqueSignature(bucket_path.orElse("DNE"), Optional.empty());
    try { //(delete log file if it exists)
        new File(log_file).delete();
    } catch (Exception e) {
    }

    ArrayList<String> args = new ArrayList<String>();
    args.addAll(Arrays.asList(global.binary_path(), "-e", logstash_config));
    if (bucket_path.isPresent()) {
        args.addAll(Arrays.asList("-l", log_file));
    }
    if (0L == requested_docs) {
        args.add("-t"); // test mode, must faster
    } //TESTED

    if (bucket_config.debug_verbosity()) {
        args.add("--debug");
    } else {
        args.add("--verbose");
    }
    ProcessBuilder logstashProcessBuilder = new ProcessBuilder(args);
    logstashProcessBuilder = logstashProcessBuilder.directory(new File(global.working_dir()))
            .redirectErrorStream(true);
    logstashProcessBuilder.environment().put("JAVA_OPTS", "");

    return logstashProcessBuilder;
}

From source file:net.sf.jabref.util.Util.java

/**
 * Automatically add links for this set of entries, based on the globally stored list of external file types. The
 * entries are modified, and corresponding UndoEdit elements added to the NamedCompound given as argument.
 * Furthermore, all entries which are modified are added to the Set of entries given as an argument.
 * <p>//from   w w  w  .ja  va 2s.c o  m
 * The entries' bibtex keys must have been set - entries lacking key are ignored. The operation is done in a new
 * thread, which is returned for the caller to wait for if needed.
 *
 * @param entries          A collection of BibEntry objects to find links for.
 * @param ce               A NamedCompound to add UndoEdit elements to.
 * @param changedEntries   MODIFIED, optional. A Set of BibEntry objects to which all modified entries is added.
 *                         This is used for status output and debugging
 * @param singleTableModel UGLY HACK. The table model to insert links into. Already existing links are not
 *                         duplicated or removed. This parameter has to be null if entries.count() != 1. The hack has been
 *                         introduced as a bibtexentry does not (yet) support the function getListTableModel() and the
 *                         FileListEntryEditor editor holds an instance of that table model and does not reconstruct it after the
 *                         search has succeeded.
 * @param metaData         The MetaData providing the relevant file directory, if any.
 * @param callback         An ActionListener that is notified (on the event dispatch thread) when the search is finished.
 *                         The ActionEvent has id=0 if no new links were added, and id=1 if one or more links were added. This
 *                         parameter can be null, which means that no callback will be notified.
 * @param diag             An instantiated modal JDialog which will be used to display the progress of the autosetting. This
 *                         parameter can be null, which means that no progress update will be shown.
 * @return the thread performing the autosetting
 */
public static Runnable autoSetLinks(final Collection<BibEntry> entries, final NamedCompound ce,
        final Set<BibEntry> changedEntries, final FileListTableModel singleTableModel, final MetaData metaData,
        final ActionListener callback, final JDialog diag) {
    final Collection<ExternalFileType> types = ExternalFileTypes.getInstance().getExternalFileTypeSelection();
    if (diag != null) {
        final JProgressBar prog = new JProgressBar(JProgressBar.HORIZONTAL, 0, types.size() - 1);
        final JLabel label = new JLabel(Localization.lang("Searching for files"));
        prog.setIndeterminate(true);
        prog.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        diag.setTitle(Localization.lang("Autosetting links"));
        diag.getContentPane().add(prog, BorderLayout.CENTER);
        diag.getContentPane().add(label, BorderLayout.SOUTH);

        diag.pack();
        diag.setLocationRelativeTo(diag.getParent());
    }

    Runnable r = new Runnable() {

        @Override
        public void run() {
            // determine directories to search in
            List<File> dirs = new ArrayList<>();
            List<String> dirsS = metaData.getFileDirectory(Globals.FILE_FIELD);
            for (String dirs1 : dirsS) {
                dirs.add(new File(dirs1));
            }

            // determine extensions
            Collection<String> extensions = new ArrayList<>();
            for (final ExternalFileType type : types) {
                extensions.add(type.getExtension());
            }

            // Run the search operation:
            Map<BibEntry, List<File>> result;
            if (Globals.prefs.getBoolean(JabRefPreferences.AUTOLINK_USE_REG_EXP_SEARCH_KEY)) {
                String regExp = Globals.prefs.get(JabRefPreferences.REG_EXP_SEARCH_EXPRESSION_KEY);
                result = RegExpFileSearch.findFilesForSet(entries, extensions, dirs, regExp);
            } else {
                result = FileUtil.findAssociatedFiles(entries, extensions, dirs);
            }

            boolean foundAny = false;
            // Iterate over the entries:
            for (Entry<BibEntry, List<File>> entryFilePair : result.entrySet()) {
                FileListTableModel tableModel;
                String oldVal = entryFilePair.getKey().getField(Globals.FILE_FIELD);
                if (singleTableModel == null) {
                    tableModel = new FileListTableModel();
                    if (oldVal != null) {
                        tableModel.setContent(oldVal);
                    }
                } else {
                    assert entries.size() == 1;
                    tableModel = singleTableModel;
                }
                List<File> files = entryFilePair.getValue();
                for (File f : files) {
                    f = FileUtil.shortenFileName(f, dirsS);
                    boolean alreadyHas = false;
                    //System.out.println("File: "+f.getPath());
                    for (int j = 0; j < tableModel.getRowCount(); j++) {
                        FileListEntry existingEntry = tableModel.getEntry(j);
                        //System.out.println("Comp: "+existingEntry.getLink());
                        if (new File(existingEntry.link).equals(f)) {
                            alreadyHas = true;
                            break;
                        }
                    }
                    if (!alreadyHas) {
                        foundAny = true;
                        ExternalFileType type;
                        Optional<String> extension = FileUtil.getFileExtension(f);
                        if (extension.isPresent()) {
                            type = ExternalFileTypes.getInstance().getExternalFileTypeByExt(extension.get());
                        } else {
                            type = new UnknownExternalFileType("");
                        }
                        FileListEntry flEntry = new FileListEntry(f.getName(), f.getPath(), type);
                        tableModel.addEntry(tableModel.getRowCount(), flEntry);

                        String newVal = tableModel.getStringRepresentation();
                        if (newVal.isEmpty()) {
                            newVal = null;
                        }
                        if (ce != null) {
                            // store undo information
                            UndoableFieldChange change = new UndoableFieldChange(entryFilePair.getKey(),
                                    Globals.FILE_FIELD, oldVal, newVal);
                            ce.addEdit(change);
                        }
                        // hack: if table model is given, do NOT modify entry
                        if (singleTableModel == null) {
                            entryFilePair.getKey().setField(Globals.FILE_FIELD, newVal);
                        }
                        if (changedEntries != null) {
                            changedEntries.add(entryFilePair.getKey());
                        }
                    }
                }
            }

            // handle callbacks and dialog
            // FIXME: The ID signals if action was successful :/
            final int id = foundAny ? 1 : 0;
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    if (diag != null) {
                        diag.dispose();
                    }
                    if (callback != null) {
                        callback.actionPerformed(new ActionEvent(this, id, ""));
                    }
                }
            });
        }
    };
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            // show dialog which will be hidden when the task is done
            if (diag != null) {
                diag.setVisible(true);
            }
        }
    });
    return r;
}

From source file:eu.mihosoft.vrl.v3d.Edge.java

public static List<Polygon> boundaryPathsWithHoles(List<Polygon> boundaryPaths) {

    List<Polygon> result = boundaryPaths.stream().map(p -> p.clone()).collect(Collectors.toList());

    List<List<Integer>> parents = new ArrayList<>();
    boolean[] isHole = new boolean[result.size()];

    for (int i = 0; i < result.size(); i++) {
        Polygon p1 = result.get(i);
        List<Integer> parentsOfI = new ArrayList<>();
        parents.add(parentsOfI);//w w  w  .j a v  a  2  s .c o m
        for (int j = 0; j < result.size(); j++) {
            Polygon p2 = result.get(j);
            if (i != j) {
                if (p2.contains(p1)) {
                    parentsOfI.add(j);
                }
            }
        }
        isHole[i] = parentsOfI.size() % 2 != 0;
    }

    int[] parent = new int[result.size()];

    for (int i = 0; i < parent.length; i++) {
        parent[i] = -1;
    }

    for (int i = 0; i < parents.size(); i++) {
        List<Integer> par = parents.get(i);

        int max = 0;
        int maxIndex = 0;
        for (int pIndex : par) {

            int pSize = parents.get(pIndex).size();

            if (max < pSize) {
                max = pSize;
                maxIndex = pIndex;
            }
        }

        parent[i] = maxIndex;

        if (!isHole[maxIndex] && isHole[i]) {

            List<Polygon> holes;

            Optional<List<Polygon>> holesOpt = result.get(maxIndex).getStorage().getValue(KEY_POLYGON_HOLES);

            if (holesOpt.isPresent()) {
                holes = holesOpt.get();
            } else {
                holes = new ArrayList<>();
                result.get(maxIndex).getStorage().set(KEY_POLYGON_HOLES, holes);
            }

            holes.add(result.get(i));
        }
    }

    return result;
}

From source file:io.leishvl.core.prov.ProvFactory.java

public static void addEditProv(final Document graph, final User editor, final String lvlId) {
    final String lvlId2 = parseParam(lvlId);
    checkArgument(editor != null, "Uninitialized editor");
    checkArgument(isNotBlank(editor.getUserid()), "Uninitialized user Id");
    checkArgument(isNotBlank(editor.getProvider()), "Uninitialized identity provider");

    final Bundle bundle = getBundle(graph);
    final Agent system = getSystem(bundle);

    // imported draft is open to future editions
    final QualifiedName editActQn = PROVENANCE.qn("edit");
    final QualifiedName revisedDraftQn = PROVENANCE.qn(LVL_PREFIX, "RevisedDraft");
    final Optional<Statement> revisedDraftOpt = ofNullable(bundle.getStatement().stream()
            .filter(stmt -> stmt instanceof Entity && revisedDraftQn.equals(((Entity) stmt).getId()))
            .findFirst().orElse(null));/*from  w  w w  . j av a 2s . c  o  m*/
    final Entity revisedDraft = (Entity) revisedDraftOpt.orElse(PROVENANCE.entity(LVL_PREFIX, "RevisedDraft"));
    if (!revisedDraftOpt.isPresent()) {
        final Activity editAct = PROVENANCE.factory().newActivity(editActQn);
        final QualifiedName objQn = PROVENANCE.qn(LVL_PREFIX, lvlId2);
        bundle.getStatement()
                .addAll(asList(editAct, revisedDraft,
                        PROVENANCE.factory().newUsed(null, editAct.getId(), objQn),
                        PROVENANCE.factory().newWasDerivedFrom(null, revisedDraft.getId(), objQn),
                        PROVENANCE.factory().newWasGeneratedBy(null, revisedDraft.getId(), editAct.getId())));
    }

    // add editor
    final QualifiedName editorQn = PROVENANCE.qn(LVL_PREFIX, editor.getUserid());
    final Optional<Statement> editorAgentOpt = ofNullable(bundle.getStatement().stream()
            .filter(stmt -> stmt instanceof Agent && editorQn.equals(((Agent) stmt).getId())).findFirst()
            .orElse(null));
    final Agent editorAgent = (Agent) editorAgentOpt.orElse(PROVENANCE.personAgent(editor));
    if (!editorAgentOpt.isPresent()) {
        bundle.getStatement()
                .addAll(asList(editorAgent,
                        PROVENANCE.factory().newActedOnBehalfOf(null, editorAgent.getId(), system.getId()),
                        PROVENANCE.factory().newWasAssociatedWith(null, editActQn, editorAgent.getId())));
    }
}

From source file:eu.mihosoft.vrl.v3d.Edge.java

/**
 * Returns a list of all boundary paths.
 *
 * @param boundaryEdges boundary edges (all paths must be closed)
 * @return/*  ww  w  .j a v a 2 s  . c  o m*/
 */
private static List<Polygon> boundaryPaths(List<Edge> boundaryEdges) {
    List<Polygon> result = new ArrayList<>();

    boolean[] used = new boolean[boundaryEdges.size()];
    int startIndex = 0;
    Edge edge = boundaryEdges.get(startIndex);
    used[startIndex] = true;

    startIndex = 1;

    while (startIndex > 0) {
        List<Vector3d> boundaryPath = new ArrayList<>();

        while (true) {
            Edge finalEdge = edge;

            boundaryPath.add(finalEdge.p1.pos);

            System.out.print("edge: " + edge.p2.pos);

            Optional<Edge> nextEdgeResult = boundaryEdges.stream().filter(e -> finalEdge.p2.equals(e.p1))
                    .findFirst();

            if (!nextEdgeResult.isPresent()) {
                System.out.println("ERROR: unclosed path:" + " no edge found with " + finalEdge.p2);
                break;
            }

            Edge nextEdge = nextEdgeResult.get();

            int nextEdgeIndex = boundaryEdges.indexOf(nextEdge);

            if (used[nextEdgeIndex]) {
                break;
            }

            edge = nextEdge;
            System.out.println("-> edge: " + edge.p1.pos);
            used[nextEdgeIndex] = true;
        }

        if (boundaryPath.size() < 3) {
            break;
        }

        result.add(Polygon.fromPoints(boundaryPath));
        startIndex = nextUnused(used);

        if (startIndex > 0) {
            edge = boundaryEdges.get(startIndex);
            used[startIndex] = true;
        }

    }

    System.out.println("paths: " + result.size());

    return result;
}

From source file:com.thinkbiganalytics.nifi.rest.support.NifiPropertyUtil.java

/**
 * Validates that the specified value is valid for the property.
 *
 * @param property the property/*from  w w w  .ja  v a  2  s.  c o m*/
 * @param value    the value to validate
 * @return {@code true} if the value is valid for the property, or {@code false} otherwise
 */
private static boolean isValidPropertyValue(@Nonnull final NifiProperty property, final String value) {
    // Check for list of allowable values
    final Optional<List<NiFiAllowableValue>> allowableValues = Optional.of(property)
            .map(NifiProperty::getPropertyDescriptor).map(NiFiPropertyDescriptor::getAllowableValues);
    if (allowableValues.isPresent()) {
        return allowableValues.get().stream().filter(allowableValue -> allowableValue.getValue().equals(value))
                .findAny().isPresent();
    }
    return true;
}

From source file:com.ikanow.aleph2.harvest.script.services.TestScriptHarvestService.java

private static DataBucketBean getTestbucket(final String full_name, final Optional<String> script,
        final Optional<String> local_script_file, Optional<String> resource_file,
        final Map<String, String> args, final List<String> required_assets) {
    final LinkedHashMap<String, Object> config = new LinkedHashMap<String, Object>();
    if (script.isPresent())
        config.put("script", script.get());
    if (local_script_file.isPresent())
        config.put("local_script_url", local_script_file.get());
    if (resource_file.isPresent())
        config.put("resource_name", resource_file.get());
    config.put("args", args);
    config.put("required_assets", required_assets);
    final List<HarvestControlMetadataBean> harvest_configs = new ArrayList<HarvestControlMetadataBean>();
    harvest_configs.add(/*from  www  .  j av a  2  s. c o  m*/
            new HarvestControlMetadataBean("harvester_1", true, null, new ArrayList<String>(), null, config));
    return BeanTemplateUtils.build(DataBucketBean.class).with(DataBucketBean::full_name, full_name)
            .with(DataBucketBean::harvest_configs, harvest_configs)
            .with(DataBucketBean::owner_id, "test_owner_id1234").done().get();
}

From source file:io.github.retz.web.JobRequestHandler.java

static String getDir(spark.Request req, spark.Response res) throws JsonProcessingException {
    Optional<Job> job;//from  w  w w. j a va  2  s .com
    try {
        job = getJobAndVerify(req);
    } catch (IOException e) {
        return MAPPER.writeValueAsString(new ErrorResponse(e.toString()));
    }

    String path = req.queryParams("path");
    LOG.debug("get-path: path={}", path);
    res.type("application/json");

    // Translating default as SparkJava's router doesn't route '.' or empty string
    if (ListFilesRequest.DEFAULT_SANDBOX_PATH.equals(path)) {
        path = "";
    }

    List ret;
    if (job.isPresent() && job.get().url() != null) {
        try {
            Pair<Integer, String> maybeJson = MesosHTTPFetcher.fetchHTTPDir(job.get().url(), path);
            if (maybeJson.left() == 200) {
                ret = MAPPER.readValue(maybeJson.right(), new TypeReference<List<DirEntry>>() {
                });
            } else {
                return MAPPER.writeValueAsString(
                        new ErrorResponse(path + ":" + maybeJson.left() + " " + maybeJson.right()));
            }
        } catch (FileNotFoundException e) {
            res.status(404);
            LOG.warn("path {} not found", path);
            return MAPPER.writeValueAsString(new ErrorResponse(path + " not found"));
        } catch (IOException e) {
            return MAPPER.writeValueAsString(new ErrorResponse(e.toString()));
        }
    } else {
        ret = Arrays.asList();
    }

    ListFilesResponse listFilesResponse = new ListFilesResponse(job, ret);
    listFilesResponse.status("ok");
    return MAPPER.writeValueAsString(listFilesResponse);
}

From source file:com.helion3.prism.api.query.QueryBuilder.java

/**
 * Builds a {@link Query} by parsing an array of arguments.
 *
 * @param parameters String[] Parameter:value list
 * @return {@link Query} Database query object
 *///w w  w . j a va 2s. c o m
public static CompletableFuture<Query> fromArguments(QuerySession session, @Nullable String[] arguments)
        throws ParameterException {
    checkNotNull(session);

    Query query = new Query();
    CompletableFuture<Query> future = new CompletableFuture<Query>();

    // Track all parameter pairs
    Map<String, String> definedParameters = new HashMap<String, String>();

    if (arguments.length > 0) {
        List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>();
        for (String arg : arguments) {
            Optional<ListenableFuture<?>> listenable;

            if (flagPattern.matcher(arg).matches()) {
                listenable = parseFlagFromArgument(session, query, arg);
            } else {
                // Get alias/value pair
                Pair<String, String> pair = getParameterKeyValue(arg);

                // Parse for handler
                listenable = parseParameterFromArgument(session, query, pair);

                // Add to list of defined
                definedParameters.put(pair.getKey(), pair.getValue());
            }

            if (listenable.isPresent()) {
                futures.add(listenable.get());
            }
        }

        if (!futures.isEmpty()) {
            ListenableFuture<List<Object>> combinedFuture = Futures.allAsList(futures);
            combinedFuture.addListener(new Runnable() {
                @Override
                public void run() {
                    future.complete(query);
                }
            }, MoreExecutors.sameThreadExecutor());
        } else {
            future.complete(query);
        }
    } else {
        future.complete(query);
    }

    if (Prism.getConfig().getNode("defaults", "enabled").getBoolean()) {
        // Require any parameter defaults
        String defaultsUsed = "";
        for (ParameterHandler handler : Prism.getParameterHandlers()) {
            boolean aliasFound = false;

            for (String alias : handler.getAliases()) {
                if (definedParameters.containsKey(alias)) {
                    aliasFound = true;
                    break;
                }
            }

            if (!aliasFound) {
                Optional<Pair<String, String>> pair = handler.processDefault(session, query);
                if (pair.isPresent()) {
                    defaultsUsed += pair.get().getKey() + ":" + pair.get().getValue() + " ";
                }
            }
        }

        // @todo should move this
        if (!defaultsUsed.isEmpty()) {
            session.getCommandSource().get().sendMessage(
                    Format.subduedHeading(Text.of(String.format("Defaults used: %s", defaultsUsed))));
        }
    }

    return future;
}