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:org.openmhealth.shim.jawbone.mapper.JawboneDataPointMapper.java

/**
 * @param listEntryNode an individual entry node from the "items" array of a Jawbone endpoint response
 * @param unixEpochTimestamp unix epoch seconds timestamp from a time property in the list entry node
 * @return the appropriate {@link ZoneId} for the timestamp parameter based on the timezones contained within the
 * list entry node/*  www.j av  a2 s  . c o  m*/
 */
static ZoneId getTimeZoneForTimestamp(JsonNode listEntryNode, Long unixEpochTimestamp) {

    Optional<JsonNode> optionalTimeZonesNode = asOptionalNode(listEntryNode, "details.tzs");
    Optional<JsonNode> optionalTimeZoneNode = asOptionalNode(listEntryNode, "details.tz");

    ZoneId zoneIdForTimestamp = ZoneOffset.UTC; // set default to Z in case problems with getting timezone

    if (optionalTimeZonesNode.isPresent() && optionalTimeZonesNode.get().size() > 0) {

        JsonNode timeZonesNode = optionalTimeZonesNode.get();

        if (timeZonesNode.size() == 1) {
            zoneIdForTimestamp = parseZone(timeZonesNode.get(0).get(TIMEZONE_ENUM_INDEX_TZ));
        } else {

            long currentLatestTimeZoneStart = 0;
            for (JsonNode timeZoneNodesEntry : timeZonesNode) {

                long timeZoneStartTime = timeZoneNodesEntry.get(TIMEZONE_ENUM_INDEX_START).asLong();

                if (unixEpochTimestamp >= timeZoneStartTime) {

                    if (timeZoneStartTime > currentLatestTimeZoneStart) { // we cannot guarantee the order of the
                        // "tzs" array and we need to find the latest timezone that started before our time

                        zoneIdForTimestamp = parseZone(timeZoneNodesEntry.get(TIMEZONE_ENUM_INDEX_TZ));
                        currentLatestTimeZoneStart = timeZoneStartTime;
                    }
                }
            }
        }
    } else if (optionalTimeZoneNode.isPresent() && !optionalTimeZoneNode.get().isNull()) {

        zoneIdForTimestamp = parseZone(optionalTimeZoneNode.get());
    }

    return zoneIdForTimestamp;
}

From source file:com.github.mavogel.ilias.utils.IOUtils.java

/**
 * Checks for valid characters in tokens.
 *
 * @param tokens the tokens @see {@link IOUtils#splitAndTrim(String)}
 * @throws IllegalArgumentException if there is an invalid token
 *///  w ww .  j  a va  2  s .  c  om
private static void checkForInvalidCharacters(final List<String> tokens) {
    Optional<String> invalidChoice = tokens.stream().filter(
            s -> !Defaults.DIGIT_PATTERN.matcher(s).matches() && !Defaults.RANGE_PATTERN.matcher(s).matches())
            .findAny();
    if (invalidChoice.isPresent())
        throw new IllegalArgumentException("Contains invalid indexes and/or ranges or an invalid wildcard!");
}

From source file:de.fosd.jdime.Main.java

/**
 * Parses the given <code>artifact</code> to an AST and attempts to find a node with the given <code>number</code>
 * in the tree. If found, the {@link DumpMode#PRETTY_PRINT_DUMP} will be used to dump the node to standard out.
 * If <code>scope</code> is not {@link KeyEnums.Type#NODE}, the method will walk up the tree to find a node that
 * fits the requested <code>scope</code> and dump it instead.
 *
 * @param artifact/*from ww w  .j  a v a  2 s. co m*/
 *         the <code>FileArtifact</code> to parse to an AST
 * @param number
 *         the number of the <code>artifact</code> in the AST to find
 * @param scope
 *         the scope to dump
 */
private static void inspectElement(FileArtifact artifact, int number, KeyEnums.Type scope) {
    ASTNodeArtifact astArtifact = new ASTNodeArtifact(artifact);
    Optional<Artifact<ASTNodeArtifact>> foundNode = astArtifact.find(number);

    if (foundNode.isPresent()) {
        Artifact<ASTNodeArtifact> element = foundNode.get();

        if (scope != KeyEnums.Type.NODE) {
            // walk tree upwards until scope fits
            while (scope != element.getType() && !element.isRoot()) {
                element = element.getParent();
            }
        }

        System.out.println(element.dump(DumpMode.PRETTY_PRINT_DUMP));
    } else {
        LOG.log(Level.WARNING, () -> "Could not find a node with number " + number + ".");
    }
}

From source file:de.fosd.jdime.Main.java

/**
 * Parses command line arguments and initializes program.
 *
 * @param context//ww w.j  a  va2s . c o  m
 *         merge context
 * @param args
 *         command line arguments
 * @return true if program should continue
 */
private static boolean parseCommandLineArgs(MergeContext context, String[] args) {
    JDimeConfig config;

    try {
        config = new JDimeConfig(args);
    } catch (ParseException e) {
        System.err.println("Failed to parse the command line arguments " + Arrays.toString(args));
        System.err.println(e.getMessage());
        System.exit(EXIT_FAILURE);
        return false;
    }

    Main.config = config;

    if (args.length == 0 || config.getBoolean(CLI_HELP).orElse(false)) {
        printCLIHelp();
        return false;
    }

    if (config.getBoolean(CLI_VERSION).orElse(false)) {
        Optional<String> commit = config.get(JDIME_COMMIT);

        if (commit.isPresent()) {
            System.out.printf("%s version %s commit %s%n", TOOLNAME, VERSION, commit.get());
        } else {
            System.out.printf("%s version %s%n", TOOLNAME, VERSION);
        }

        return false;
    }

    Optional<String> mode = config.get(CLI_MODE).map(String::toLowerCase);

    if (mode.isPresent() && MODE_LIST.equals(mode.get())) {
        printStrategies();
        return false;
    }

    context.configureFrom(config);
    return true;
}

From source file:de.hybris.platform.acceleratorstorefrontcommons.tags.Functions.java

public static boolean isQuoteUserSalesRep() {
    final UserModel userModel = getQuoteUserIdentificationStrategy(getCurrentRequest()).getCurrentQuoteUser();
    final Optional<QuoteUserType> quoteUserTypeOptional = getQuoteUserTypeIdentificationStrategy(
            getCurrentRequest()).getCurrentQuoteUserType(userModel);
    return quoteUserTypeOptional.isPresent() && QuoteUserType.SELLER.equals(quoteUserTypeOptional.get());
}

From source file:de.hybris.platform.acceleratorstorefrontcommons.tags.Functions.java

public static boolean isQuoteUserSellerApprover() {
    final UserModel userModel = getQuoteUserIdentificationStrategy(getCurrentRequest()).getCurrentQuoteUser();
    final Optional<QuoteUserType> quoteUserTypeOptional = getQuoteUserTypeIdentificationStrategy(
            getCurrentRequest()).getCurrentQuoteUserType(userModel);
    return quoteUserTypeOptional.isPresent()
            && QuoteUserType.SELLERAPPROVER.equals(quoteUserTypeOptional.get());
}

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

public static String getDir(spark.Request req, spark.Response res) throws IOException {
    int id = Integer.parseInt(req.params(":id"));

    String path = req.queryParams("path");
    Optional<Job> job = JobQueue.getJob(id);

    LOG.debug("get-path: id={}, path={}", id, 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 = "";
    }//from  w w  w .  jav  a 2 s  .c  o m

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

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

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

public static String schedule(Request req, Response res) throws IOException, InterruptedException {
    ScheduleRequest scheduleRequest = MAPPER.readValue(req.bodyAsBytes(), ScheduleRequest.class);
    res.type("application/json");
    Optional<Application> maybeApp = Applications.get(scheduleRequest.job().appid()); // TODO check owner right here
    if (!maybeApp.isPresent()) {
        // TODO: this warn log cannot be written in real stable release
        LOG.warn("No such application loaded: {}", scheduleRequest.job().appid());
        ErrorResponse response = new ErrorResponse("No such application: " + scheduleRequest.job().appid());
        res.status(404);//from   w  w  w .ja v  a 2s  .  c  o  m
        return MAPPER.writeValueAsString(response);

    } else if (maybeApp.get().enabled()) {

        validateOwner(req, maybeApp.get());

        Job job = scheduleRequest.job();
        if (scheduler.isPresent()) {
            if (!scheduler.get().validateJob(job)) {
                String msg = "Job " + job.toString() + " does not fit system limit "
                        + scheduler.get().maxJobSize();
                // TODO: this warn log cannot be written in real stable release
                LOG.warn(msg);
                halt(400, msg);
            }
        }

        job.schedule(JobQueue.issueJobId(), TimestampHelper.now());

        JobQueue.push(job);
        if (scheduler.isPresent() && driver.isPresent()) {
            LOG.info("Trying invocation from offer stock: {}", job);
            scheduler.get().maybeInvokeNow(driver.get(), job);

        }

        ScheduleResponse scheduleResponse = new ScheduleResponse(job);
        scheduleResponse.ok();
        LOG.info("Job '{}' at {} has been scheduled at {}.", job.cmd(), job.appid(), job.scheduled());

        res.status(201);
        return MAPPER.writeValueAsString(scheduleResponse);

    } else {
        // Application is currently disabled
        res.status(401);
        ErrorResponse response = new ErrorResponse("Application " + maybeApp.get().getAppid() + " is disabled");
        return MAPPER.writeValueAsString(response);
    }
}

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

static String kill(Request req, spark.Response res) throws JsonProcessingException {
    LOG.debug("kill", req.params(":id"));
    res.type("application/json");
    int id = Integer.parseInt(req.params(":id"));

    Optional<Job> maybeJob;
    try {//from www .  j ava2s .  c om
        maybeJob = getJobAndVerify(req);
    } catch (IOException e) {
        return MAPPER.writeValueAsString(new ErrorResponse(e.toString()));
    }

    if (!maybeJob.isPresent()) {
        res.status(404);
        Response response = new ErrorResponse("No such job: " + id);
        response.status("No such job: " + id);
        return MAPPER.writeValueAsString(response);
    }

    Optional<Boolean> result = Stanchion.call(() -> {
        Optional<Job> maybeJob2 = JobQueue.cancel(id, "Canceled by user");

        if (maybeJob2.isPresent()) {
            Job job = maybeJob2.get();
            // There's a slight pitfall between cancel above and kill below where
            // no kill may be sent, RetzScheduler is exactly in resourceOffers and being scheduled.
            // Then this protocol returns false for sure.
            if (job.taskId() != null && !job.taskId().isEmpty() && driver.isPresent()) {
                Protos.TaskID taskId = Protos.TaskID.newBuilder().setValue(job.taskId()).build();
                Protos.Status status = driver.get().killTask(taskId);
                LOG.info("Job id={} was running and killed. status={}, taskId={}", job.id(), status,
                        job.taskId());
            }
            return job.state() == Job.JobState.KILLED;
        }
        // Job is already finished or killed, no more running nor runnable, or something is wrong
        return false;
    });

    Response response;
    if (result.isPresent() && result.get()) {
        response = new KillResponse();
        res.status(200);
        response.ok();
    } else {
        res.status(500);
        response = new ErrorResponse();
        response.status("Can't kill job - due to unknown reason");
    }

    return MAPPER.writeValueAsString(response);
}

From source file:io.gravitee.management.service.impl.ApplicationServiceImpl.java

private static ApplicationEntity convert(Application application) {
    ApplicationEntity applicationEntity = new ApplicationEntity();

    applicationEntity.setId(application.getId());
    applicationEntity.setName(application.getName());
    applicationEntity.setDescription(application.getDescription());
    applicationEntity.setType(application.getType());

    applicationEntity.setCreatedAt(application.getCreatedAt());
    applicationEntity.setUpdatedAt(application.getUpdatedAt());

    if (application.getMembers() != null) {
        final Optional<Membership> member = application.getMembers().stream()
                .filter(membership -> MembershipType.PRIMARY_OWNER.equals(membership.getMembershipType()))
                .findFirst();//from w w w.j a v a  2s .  co m
        if (member.isPresent()) {
            final User user = member.get().getUser();
            final PrimaryOwnerEntity primaryOwnerEntity = new PrimaryOwnerEntity();
            primaryOwnerEntity.setUsername(user.getUsername());
            primaryOwnerEntity.setLastname(user.getLastname());
            primaryOwnerEntity.setFirstname(user.getFirstname());
            primaryOwnerEntity.setEmail(user.getEmail());
            applicationEntity.setPrimaryOwner(primaryOwnerEntity);
        }
    }

    return applicationEntity;
}