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:net.sourceforge.fullsync.cli.Main.java

public static void finishStartup(Injector injector) {
    RuntimeConfiguration rt = injector.getInstance(RuntimeConfiguration.class);
    Preferences preferences = injector.getInstance(Preferences.class);
    Scheduler scheduler = injector.getInstance(Scheduler.class);
    ProfileManager profileManager = injector.getInstance(ProfileManager.class);
    Synchronizer synchronizer = injector.getInstance(Synchronizer.class);
    Optional<String> profile = rt.getProfileToRun();
    profileManager.loadProfiles();//from www  .j  a v a2  s .  co  m
    if (profile.isPresent()) {
        handleRunProfile(synchronizer, profileManager, profile.get());
    }
    if (rt.isDaemon().orElse(false).booleanValue()) {
        daemonSchedulerListener = injector.getInstance(DaemonSchedulerListener.class);
        scheduler.start();
    }
    if (preferences.getAutostartScheduler()) {
        scheduler.start();
    }
}

From source file:com.ikanow.aleph2.data_model.utils.ProcessUtils.java

/**
 * Starts the given process by calling process_builder.start();
 * Records the started processes pid and start date.
 *  //w  w w .  jav  a  2  s . c  o  m
 * @param process_builder
 * @throws IOException 
 * @return returns any error in _1(), the pid in _2()
 */
public static Tuple2<String, String> launchProcess(final ProcessBuilder process_builder,
        final String application_name, final DataBucketBean bucket, final String aleph_root_path,
        final Optional<Tuple2<Long, Integer>> timeout_kill) {
    try {
        if (timeout_kill.isPresent()) {
            final Stream<String> timeout_stream = Stream.of("timeout", "-s", timeout_kill.get()._2.toString(),
                    timeout_kill.get()._1.toString());
            process_builder.command(Stream.concat(timeout_stream, process_builder.command().stream())
                    .collect(Collectors.toList()));
        }

        //starts the process, get pid back
        logger.debug("Starting process: " + process_builder.command().toString());
        final Process px = process_builder.start();
        String err = null;
        String pid = null;
        if (!px.isAlive()) {
            err = "Unknown error: " + px.exitValue() + ": "
                    + process_builder.command().stream().collect(Collectors.joining(" "));
            // (since not capturing output)
        } else {
            pid = getPid(px);
            //get the date on the pid file from /proc/<pid>
            final long date = getDateOfPid(pid);
            //record pid=date to aleph_root_path/pid_manager/bucket._id/application_name
            storePid(application_name, bucket, aleph_root_path, pid, date);
        }
        return Tuples._2T(err, pid);

    } catch (Throwable t) {
        return Tuples._2T(ErrorUtils.getLongForm("{0}", t), null);
    }
}

From source file:com.spotify.styx.docker.KubernetesPodEventTranslator.java

public static List<Event> translate(WorkflowInstance workflowInstance, RunState state, Action action, Pod pod,
        Stats stats) {/* w w  w. j a va2s  . c  om*/

    if (action == Watcher.Action.DELETED) {
        return emptyList();
    }

    final List<Event> generatedEvents = Lists.newArrayList();
    final Optional<Event> hasError = isInErrorState(workflowInstance, pod);

    if (hasError.isPresent()) {
        switch (state.state()) {
        case PREPARE:
        case SUBMITTED:
        case RUNNING:
            generatedEvents.add(hasError.get());

        default:
            // no event
        }

        return generatedEvents;
    }

    final PodStatus status = pod.getStatus();
    final String phase = status.getPhase();

    boolean exited = false;
    boolean started = false;
    Optional<Integer> exitCode = Optional.empty();

    switch (phase) {
    case "Running":
        // check that the styx container is ready
        started = status.getContainerStatuses().stream()
                .anyMatch(IS_STYX_CONTAINER.and(ContainerStatus::getReady));
        break;

    case "Succeeded":
    case "Failed":
        exited = true;
        exitCode = pod.getStatus().getContainerStatuses().stream().filter(IS_STYX_CONTAINER)
                .map(cs -> getExitCodeIfValid(workflowInstance.toKey(), pod, cs, stats))
                .filter(Optional::isPresent).map(Optional::get).findFirst();
        break;

    default:
        // do nothing
    }

    if (started) {
        switch (state.state()) {
        case PREPARE:
        case SUBMITTED:
            generatedEvents.add(Event.started(workflowInstance));

        default:
            // no event
        }
    }

    if (exited) {
        switch (state.state()) {
        case PREPARE:
        case SUBMITTED:
            generatedEvents.add(Event.started(workflowInstance));
            // intentional fall-through

        case RUNNING:
            generatedEvents.add(Event.terminate(workflowInstance, exitCode));
            break;

        default:
            // no event
        }
    }

    return generatedEvents;
}

From source file:lumbermill.internal.influxdb.InfluxDBClient.java

/**
 * Creates  Points based on the event and config
 *///from  www .j  a v  a 2 s .  c o m
private static Observable<Point> buildPoint(MapWrap config, StringTemplate measurementTemplate,
        JsonEvent jsonEvent) {

    final MapWrap fieldsConfig = MapWrap.of(config.getObject("fields"));
    final List<String> excludeTags = config.getObject("excludeTags", DEFAULT_EXCLUDED_TAGS);

    // One field is required, otherwise the point will not be created
    boolean addedAtLeastOneField = false;
    Optional<String> measurementOptional = measurementTemplate.format(jsonEvent);
    if (!measurementOptional.isPresent()) {
        LOGGER.debug("Failed to extract measurement using {}, not points will be created",
                measurementTemplate.original());
        return Observable.empty();
    }
    Point.Builder pointBuilder = Point.measurement(measurementOptional.get());

    for (Object entry1 : fieldsConfig.toMap().entrySet()) {
        Map.Entry<String, String> entry = (Map.Entry) entry1;
        StringTemplate fieldName = StringTemplate.compile(entry.getKey());
        String valueField = entry.getValue();

        JsonNode node = jsonEvent.unsafe().get(valueField);
        if (node == null) {
            LOGGER.debug("Failed to extract any field for {}", valueField);
            continue;
        }

        Optional<String> formattedFieldNameOptional = fieldName.format(jsonEvent);
        if (!formattedFieldNameOptional.isPresent()) {
            LOGGER.debug("Failed to extract any field for {}", fieldName.original());
            continue;
        }

        addedAtLeastOneField = true;

        if (node.isNumber()) {
            pointBuilder.addField(formattedFieldNameOptional.get(), node.asDouble());
        } else if (node.isBoolean()) {
            pointBuilder.addField(formattedFieldNameOptional.get(), node.asBoolean());
        } else {
            pointBuilder.addField(formattedFieldNameOptional.get(), node.asText());
        }
    }

    Iterator<String> stringIterator = jsonEvent.unsafe().fieldNames();
    while (stringIterator.hasNext()) {
        String next = stringIterator.next();
        if (!excludeTags.contains(next)) {
            pointBuilder.tag(next, jsonEvent.valueAsString(next));
        }
    }

    Optional<String> timeField = config.exists("time") ? Optional.of(config.asString("time"))
            : Optional.empty();
    TimeUnit precision = config.getObject("precision", TimeUnit.MILLISECONDS);

    // Override @timestamp with a ISO_8601 String or a numerical value
    if (timeField.isPresent() && jsonEvent.has(config.asString("time"))) {

        if (jsonEvent.unsafe().get(timeField.get()).isTextual()) {
            pointBuilder.time(ZonedDateTime
                    .parse(jsonEvent.valueAsString("@timestamp"), DateTimeFormatter.ISO_OFFSET_DATE_TIME)
                    .toInstant().toEpochMilli(), precision);
        } else {
            pointBuilder.time(jsonEvent.asLong(timeField.get()), precision);
        }
    } else {
        // If not overriden, check if timestamp exists and use that
        if (jsonEvent.has("@timestamp")) {
            pointBuilder.time(ZonedDateTime
                    .parse(jsonEvent.valueAsString("@timestamp"), DateTimeFormatter.ISO_OFFSET_DATE_TIME)
                    .toInstant().toEpochMilli(), precision);
        }
    }

    if (!addedAtLeastOneField) {
        LOGGER.debug("Could not create a point since no fields where added");
        return Observable.empty();
    }

    Point point = pointBuilder.build();
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Point to be stored {}", point.toString());
    }
    return Observable.just(point);
}

From source file:com.baifendian.swordfish.common.storm.StormRestUtil.java

/**
 * ???ID,???ID//from   w  w w  .  j a v a  2  s . co m
 */
public static String getTopologyId(String topologyName) throws IOException {
    Optional<TopologyDto> result = getTopologySummary().getTopologies().stream()
            .filter(t -> StringUtils.equals(t.getName(), topologyName)).findFirst();

    if (result.isPresent()) {
        return result.get().getId();
    }

    return StringUtils.EMPTY;
}

From source file:com.hurence.logisland.plugin.PluginManager.java

private static void removePlugin(String artifact) {
    Optional<ModuleInfo> moduleInfo = findPluginMeta().entrySet().stream()
            .filter(e -> artifact.equals(e.getKey().getArtifact())).map(Map.Entry::getKey).findFirst();
    if (moduleInfo.isPresent()) {
        String filename = moduleInfo.get().getSourceArchive();
        System.out.println("Removing component jar: " + filename);
        if (!new File(filename).delete()) {
            System.err.println("Unable to delete file " + artifact);
            System.exit(-1);/*  www.  j  a  v a 2  s .c  o  m*/
        }

    } else {
        System.err.println("Found no installed component matching artifact " + artifact);
        System.exit(-1);
    }
}

From source file:com.liferay.blade.cli.util.Prompter.java

private static Optional<Boolean> _getBooleanAnswer(String questionWithPrompt, InputStream inputStream,
        PrintStream printStream, Optional<Boolean> defaultAnswer) {

    Optional<Boolean> answer = null;

    try (CloseShieldInputStream closeShieldInputStream = new CloseShieldInputStream(inputStream);
            Scanner scanner = new Scanner(closeShieldInputStream)) {

        while ((answer == null) || !answer.isPresent()) {
            printStream.println(questionWithPrompt);

            String readLine = null;

            while (((answer == null) || !answer.isPresent()) && !Objects.equals(answer, defaultAnswer)
                    && scanner.hasNextLine()) {

                readLine = scanner.nextLine();

                if (readLine != null) {
                    readLine = readLine.toLowerCase();

                    switch (readLine.trim()) {
                    case "y":
                    case "yes":
                        answer = Optional.of(true);

                        break;
                    case "n":
                    case "no":
                        answer = Optional.of(false);

                        break;
                    default:
                        if (defaultAnswer.isPresent()) {
                            answer = defaultAnswer;
                        } else {
                            printStream.println("Unrecognized input: " + readLine);

                            continue;
                        }/*from   w w w . j a  v a2 s  .c  om*/

                        break;
                    }
                } else {
                    answer = defaultAnswer;
                }
            }
        }
    } catch (IllegalStateException ise) {
        throw new RuntimeException(ise);
    } catch (Exception exception) {
        if (defaultAnswer.isPresent()) {
            answer = defaultAnswer;
        }
    }

    return answer;
}

From source file:info.archinnov.achilles.internals.schema.SchemaValidator.java

private static void validateDSESearchIndex(Class<?> entityClass, TableMetadata tableMetadata) {
    final String tableName = tableMetadata.getName().toLowerCase();
    final String keyspaceName = tableMetadata.getKeyspace().getName().toLowerCase();
    final String indexName = keyspaceName + "_" + tableName + "_solr_query_index";
    final Optional<IndexMetadata> indexMeta = Optional.ofNullable(tableMetadata.getIndex(indexName));

    validateBeanMappingTrue(indexMeta.isPresent(), "Index name %s for entity '%s' cannot be found", indexName,
            entityClass);//from w ww  .  j a  v  a2s  . c om

    final IndexMetadata indexMetadata = indexMeta.get();
    final String indexClassName = indexMetadata.getIndexClassName();
    validateBeanMappingTrue(indexClassName.equals(DSESearchInfoContext.DSE_SEARCH_INDEX_CLASSNAME),
            "Index class name %s for entity '%s' should be %s", indexClassName, entityClass,
            DSESearchInfoContext.DSE_SEARCH_INDEX_CLASSNAME);
}

From source file:alfio.model.system.Configuration.java

private static ConfigurationPathKey from(Optional<Integer> organizationId, Optional<Integer> eventId,
        Optional<Integer> ticketCategoryId, ConfigurationKeys key) {
    boolean organizationAvailable = organizationId.isPresent();
    boolean eventAvailable = eventId.isPresent();
    boolean categoryAvailable = ticketCategoryId.isPresent();
    ConfigurationPathLevel mostSensible = Arrays.stream(ConfigurationPathLevel.values())
            .sorted(Comparator.<ConfigurationPathLevel>naturalOrder().reversed()).filter(
                    path -> path == ConfigurationPathLevel.ORGANIZATION && organizationAvailable
                            || path == ConfigurationPathLevel.EVENT && organizationAvailable && eventAvailable
                            || path == ConfigurationPathLevel.TICKET_CATEGORY && organizationAvailable
                                    && eventAvailable && categoryAvailable)
            .findFirst().orElse(ConfigurationPathLevel.SYSTEM);
    switch (mostSensible) {
    case ORGANIZATION:
        return getOrganizationConfiguration(organizationId.get(), key);
    case EVENT:/*  ww w.j a  va  2s  .  c o m*/
        return getEventConfiguration(organizationId.get(), eventId.get(), key);
    case TICKET_CATEGORY:
        return getTicketCategoryConfiguration(organizationId.get(), eventId.get(), ticketCategoryId.get(), key);
    }
    return getSystemConfiguration(key);
}

From source file:com.formkiq.core.form.FormFinder.java

/**
 * Find {@link FormJSONField}./*w  w  w.  j  av  a2 s  .c  om*/
 * @param archive {@link ArchiveDTO}
 * @param documentfieldname {@link String}
 * @return {@link Optional} {@link FormJSONField}
 */
public static Optional<FormJSONField> findField(final ArchiveDTO archive, final String documentfieldname) {

    Optional<FormJSONField> op = Optional.empty();
    List<WorkflowOutputFormField> fields = stream(archive.getWorkflow());
    Optional<WorkflowOutputFormField> o = fields.stream()
            .filter(s -> s.getDocumentfieldname().equals(documentfieldname)).findFirst();

    if (o.isPresent()) {
        String fuuid = extractLabelAndValue(o.get().getForm()).getRight();
        String fid = extractLabelAndValue(o.get().getField()).getRight();

        FormJSON form = archive.getForm(fuuid);
        op = FormFinder.findField(form, NumberUtils.toInt(fid, -1));
    }

    return op;
}