Example usage for java.util Optional get

List of usage examples for java.util Optional get

Introduction

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

Prototype

public T get() 

Source Link

Document

If a value is present, returns the value, otherwise throws NoSuchElementException .

Usage

From source file:com.unidev.polycms.hateoas.controller.StorageQueryController.java

@GetMapping(value = "/storage/{storage}/poly/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public HateoasResponse fetchPoly(@PathVariable("storage") String storage, @PathVariable("id") String id) {
    if (!polyCore.existTenant(storage)) {
        LOG.warn("Not found storage {}", storage);
        throw new StorageNotFoundException("Storage " + storage + " not found");
    }/*from  ww w.  j ava  2  s  .  c  o  m*/
    SQLitePolyStorage sqLitePolyStorage = polyCore.fetchSqliteStorage(storage);

    Optional<PolyRecord> polyRecord = sqLitePolyStorage.fetchPoly(id);
    polyRecord.orElseThrow(StorageNotFoundException::new);
    HateoasResponse hateoasResponse = hateoasResponse().data(polyRecord.get());
    hateoasResponse.add(linkTo(StorageIndexController.class).slash("storage").slash(storage).slash("poly")
            .slash(id).withSelfRel());
    return hateoasResponse;
}

From source file:se.omegapoint.facepalm.client.controllers.ImageController.java

@RequestMapping("/image")
public String image(final @RequestParam String id, final Model model) {
    final Optional<ImagePost> image = imageAdapter.getImage(id);
    if (!image.isPresent()) {
        return "redirect:/404";
    }//from  w  w w . j  a va2 s.com

    final List<ImageComment> comments = imageAdapter.getCommentsForImage(image.get().id);
    model.addAttribute("image", image.get());
    model.addAttribute("comments", comments);
    return "image";
}

From source file:org.cyberjos.jcconf2016.node.CloudNodeImpl.java

/**
 * {@inheritDoc}/*w  ww.ja va2  s .c  o m*/
 */
@Override
public void memberRemoved(final MembershipEvent membershipEvent) {
    final String removedId = membershipEvent.getMember().getUuid();

    logger.info("[{}] Found a node removed from cluster: {}", this.nodeName, removedId);

    final Optional<NodeRecord> masterNode = this.hazelcastHelper.getMasterNodeRecord();
    if (!masterNode.isPresent() || StringUtils.equals(removedId, masterNode.get().getMemberId())) {
        logger.info("[{}] The master is removed. Trying to be the master node.", this.nodeName);
        this.hazelcastHelper.setMaster(this);
    } else {
        logger.info("[{}] The current master node: {}", this.nodeName, masterNode.get());
    }
}

From source file:io.mapzone.controller.vm.http.AuthTokenValidator.java

/**
 * /*from   www . j  a v a2  s . c om*/
 *
 * @throws HttpProvisionRuntimeException If project does not exists.
 */
public boolean checkAuthToken() {
    ProjectInstanceIdentifier pid = new ProjectInstanceIdentifier(request);

    // check param token; ignore parameter char case
    Optional<String> requestToken = requestParameter(REQUEST_PARAM_TOKEN);
    if (requestToken.isPresent()) {
        if (!isValidToken(requestToken.get(), pid)) {
            throw new HttpProvisionRuntimeException(401, "Given auth token is not valid for this project.");
        }
        return true;
    }

    // check path parts
    String path = StringUtils.defaultString(request.getPathInfo());
    for (String part : StringUtils.split(path, '/')) {
        if (isValidToken(part, pid)) {
            return true;
        }
    }
    return false;
}

From source file:it.lic.cli.Main.java

private void run(final CommandLine cli) throws Exception {
    final Wallet wallet = new Wallet.Default(new FileStorage(new System.Default()));
    if (cli.hasOption("h")) {
        this.help();
    } else if (cli.hasOption("l")) {
        final LicenseKeyPair lkp = wallet.licenseKeyPair(cli.getOptionValue("l"));
        java.lang.System.out.println(String.format("[%s] Public key: %s", lkp.name(),
                new String(Base64.getEncoder().encode(lkp.publicKey().getEncoded()))));
    } else if (cli.hasOption("L")) {
        final Iterator<License> licenses = wallet.licenses(wallet.licenseKeyPair(cli.getOptionValue("L")), "");
        while (licenses.hasNext()) {
            License current = licenses.next();
            java.lang.System.out.println(String.format("%s\t%s\t%s\t%s", current.name(), current.issuer(),
                    current.until(), current.encode()));
        }//from   w  w w  .  j  a  va  2s . com
    } else if (cli.hasOption("k")) {
        final LicenseKeyPair lkp = wallet.newLicenseKeyPair(cli.getOptionValue("k"));
        java.lang.System.out.println(String.format("new keypair created: %s",
                new String(Base64.getEncoder().encode(lkp.publicKey().getEncoded()))));
    } else if (cli.hasOption("K")) {
        final Calendar expire = Calendar.getInstance();
        expire.add(Calendar.YEAR, 1);
        Optional<License> license = wallet.hasLicenseFor(wallet.licenseKeyPair("prometeo"),
                cli.getOptionValue("K"));
        if (license.isPresent()) {
            java.lang.System.out.println(String.format("license already esists: %s", license.get().encode()));
        } else {
            final License newlicense = wallet.newLicense(cli.getOptionValue("K"),
                    wallet.licenseKeyPair("prometeo"), cli.getOptionValue("K"), expire.getTime(),
                    Collections.emptyMap());
            java.lang.System.out.println(String.format("new license created: %s", newlicense.encode()));
        }
    }
}

From source file:org.obiba.mica.micaConfig.rest.DataAccessResource.java

@GET
@Path("/form")
@Timed//w ww  . jav a2  s . c om
public Mica.DataAccessFormDto getDataAccessForm(@QueryParam("lang") String lang) {
    Optional<DataAccessForm> d = dataAccessFormService.find();

    if (!d.isPresent())
        throw NoSuchDataAccessFormException.withDefaultMessage();

    DataAccessForm dataAccessForm = d.get();
    Mica.DataAccessFormDto.Builder builder = Mica.DataAccessFormDto.newBuilder(dtos.asDto(dataAccessForm))
            .clearProperties().clearPdfTemplates();

    String langTag = !Strings.isNullOrEmpty(lang) ? Locale.forLanguageTag(lang).toLanguageTag()
            : LanguageTag.UNDETERMINED;

    Map<String, LocalizedString> properties = dataAccessForm.getProperties().entrySet().stream()
            .map(e -> Maps.immutableEntry(e.getKey(),
                    new LocalizedString().forLanguageTag(langTag, e.getValue().get(langTag))))
            .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

    builder.addAllProperties(dtos.asDtoList(properties));

    return builder.build();
}

From source file:com.netflix.genie.core.jobs.workflow.impl.ClusterTask.java

/**
 * {@inheritDoc}/*from  w  w  w  .ja v  a 2 s.com*/
 */
@Override
public void executeTask(@NotNull final Map<String, Object> context) throws GenieException, IOException {
    final long start = System.nanoTime();
    try {
        final JobExecutionEnvironment jobExecEnv = (JobExecutionEnvironment) context
                .get(JobConstants.JOB_EXECUTION_ENV_KEY);
        final String jobWorkingDirectory = jobExecEnv.getJobWorkingDir().getCanonicalPath();
        final String genieDir = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER
                + JobConstants.GENIE_PATH_VAR;
        final Writer writer = (Writer) context.get(JobConstants.WRITER_KEY);
        log.info("Starting Cluster Task for job {}", jobExecEnv.getJobRequest().getId());

        final String clusterId = jobExecEnv.getCluster().getId()
                .orElseThrow(() -> new GeniePreconditionException("No cluster id found"));

        // Create the directory for this application under applications in the cwd
        createEntityInstanceDirectory(genieDir, clusterId, AdminResources.CLUSTER);

        // Create the config directory for this id
        createEntityInstanceConfigDirectory(genieDir, clusterId, AdminResources.CLUSTER);

        // Get the set up file for cluster and add it to source in launcher script
        final Optional<String> setupFile = jobExecEnv.getCluster().getSetupFile();
        if (setupFile.isPresent()) {
            final String clusterSetupFile = setupFile.get();
            if (StringUtils.isNotBlank(clusterSetupFile)) {
                final String localPath = super.buildLocalFilePath(jobWorkingDirectory, clusterId,
                        clusterSetupFile, FileType.SETUP, AdminResources.CLUSTER);

                fts.getFile(clusterSetupFile, localPath);

                super.generateSetupFileSourceSnippet(clusterId, "Cluster:", localPath, writer,
                        jobWorkingDirectory);
            }
        }

        // Iterate over and get all configuration files
        for (final String configFile : jobExecEnv.getCluster().getConfigs()) {
            final String localPath = super.buildLocalFilePath(jobWorkingDirectory, clusterId, configFile,
                    FileType.CONFIG, AdminResources.CLUSTER);
            fts.getFile(configFile, localPath);
        }
        log.info("Finished Cluster Task for job {}", jobExecEnv.getJobRequest().getId());
    } finally {
        final long finish = System.nanoTime();
        this.timer.record(finish - start, TimeUnit.NANOSECONDS);
    }
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.core.DataProcessor.java

private long calculateMetric(@NonNull List<SolutionPerJob> spjList,
        BiConsumer<SolutionPerJob, Double> resultSaver, Consumer<SolutionPerJob> ifEmpty) {
    //to support also parallel stream.
    AtomicLong executionTime = new AtomicLong();

    spjList.forEach(spj -> {/*from w ww. j  av  a  2s .co m*/
        Pair<Optional<Double>, Long> result = simulateClass(spj);
        executionTime.addAndGet(result.getRight());
        Optional<Double> optionalValue = result.getLeft();
        if (optionalValue.isPresent())
            resultSaver.accept(spj, optionalValue.get());
        else
            ifEmpty.accept(spj);
    });

    return executionTime.get();
}

From source file:cats.twitter.webapp.controller.module.ApiController.java

/**
 * Modules have to query here when they want to retrieve a corpus.
 * @param token The token sent in the initialisation request (/init)
 * @param from (not required) Pagination
 * @param to (not required) Pagination/* w  w w.  j a  va 2  s  .  c  o  m*/
 * @return The list of tweets of the corpus in JSON
 */
// @CrossOrigin(origins = "http://localhost:3000")
@RequestMapping(value = "/api", method = RequestMethod.GET)
public List<Tweet> api(@RequestHeader("token") String token,
        @RequestParam(value = "from", required = false) Integer from,
        @RequestParam(value = "to", required = false) Integer to) {
    Optional<Request> req = reqRepository.findOneByToken(token);
    if (!req.isPresent()) {
        throw new IllegalAccessError("Please verify your token!");
    }
    Corpus corpus = req.get().getCorpus();

    if (from == null)
        from = 0;
    if (to == null)
        to = Math.toIntExact(tweetRepository.countByCorpusId(corpus.getId()));

    return tweetRepository.findByCorpusId(corpus.getId(), new ChunkRequest(from, to - from)).getContent();

}

From source file:com.github.mrstampy.gameboot.metrics.GameBootMetricsHelper.java

public void stopTimer(Optional<Context> ctx) {
    if (ctx.isPresent())
        ctx.get().stop();
}