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.rockagen.gnext.service.spring.security.extension.ExTokenAuthentication.java

/**
 * <p>// w w w.  ja  va2  s . co m
 * <pre>
 * token = base64(expirationTime + ":" + uid) + "." + base64(hmac(expirationTime + ":" + uid + ":" + password))
 *
 * expirationTime:    The date and time when the token expires,expressed in milliseconds
 * uid:          As identifiable to the UserDetailsService
 * password:          That matches the one in the retrieved UserDetails
 *     </pre>
 * </p>
 *
 * @param uid uid
 * @return new token,null if uid not exist or disabled
 */
public String newToken(String uid) {
    Optional<AuthUser> u = authUserServ.load(uid);

    if (u.filter(AuthUser::enabled).isPresent()) {
        String passwd = u.get().getPassword();
        long expirationTime = System.currentTimeMillis() + expiredTime;

        String partA = expirationTime + ":" + uid;
        String partB = hmac(uid, String.valueOf(expirationTime), passwd);
        String token = CommUtil.encodeBase64(partA) + "." + CommUtil.encodeBase64(partB);
        return token;
    }
    return null;
}

From source file:org.sonarqube.shell.commands.SonarSession.java

<T> Optional<T> get(String path, Class<T> clazz, Optional<Map<String, String>> params) {
    try {/*from ww w.ja va 2s  .c o  m*/
        WebTarget resource = rootContext.path(path);
        if (params.isPresent()) {
            for (Map.Entry<String, String> entry : params.get().entrySet()) {
                resource = resource.queryParam(entry.getKey(), entry.getValue());
            }
        }
        return Optional.of(resource.request(MediaType.APPLICATION_JSON_TYPE).get(clazz));
    } catch (ProcessingException | NotFoundException e) {
        LOGGER.error("Failed to get the resource {} and convert it to {}", path, clazz.getName());
    }
    return empty();
}

From source file:org.fcrepo.camel.ldpath.FedoraProvider.java

@Override
public List<String> buildRequestUrl(final String resourceUri, final Endpoint endpoint) {
    LOGGER.debug("Processing: " + resourceUri);
    Objects.requireNonNull(resourceUri);
    try {//from  w  w  w .j a  va2  s  .c  o m
        final Optional<String> nonRdfSourceDescUri = getNonRDFSourceDescribedByUri(resourceUri);
        if (nonRdfSourceDescUri.isPresent()) {
            return Collections.singletonList(nonRdfSourceDescUri.get());
        }
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
    return Collections.singletonList(resourceUri);
}

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

/**
 * {@inheritDoc}//www  .j  ava2 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 Command Task for job {}", jobExecEnv.getJobRequest().getId());

        final String commandId = jobExecEnv.getCommand().getId()
                .orElseThrow(() -> new GeniePreconditionException("No command id found"));

        // Create the directory for this command under command dir in the cwd
        createEntityInstanceDirectory(genieDir, commandId, AdminResources.COMMAND);

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

        // Get the setup file if specified and add it as source command in launcher script
        final Optional<String> setupFile = jobExecEnv.getCommand().getSetupFile();
        if (setupFile.isPresent()) {
            final String commandSetupFile = setupFile.get();
            if (StringUtils.isNotBlank(commandSetupFile)) {
                final String localPath = super.buildLocalFilePath(jobWorkingDirectory, commandId,
                        commandSetupFile, FileType.SETUP, AdminResources.COMMAND);

                fts.getFile(commandSetupFile, localPath);

                super.generateSetupFileSourceSnippet(commandId, "Command:", localPath, writer,
                        jobWorkingDirectory);
            }
        }

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

From source file:net.sf.jabref.logic.journals.JournalAbbreviationRepository.java

public Optional<String> getNextAbbreviation(String text) {
    Optional<Abbreviation> abbreviation = getAbbreviation(text);

    if (!abbreviation.isPresent()) {
        return Optional.empty();
    }//w  w  w. j  a  v  a  2s.c  o  m

    Abbreviation abbr = abbreviation.get();
    return Optional.of(abbr.getNext(text));
}

From source file:net.sf.jabref.logic.journals.JournalAbbreviationRepository.java

public Optional<String> getMedlineAbbreviation(String text) {
    Optional<Abbreviation> abbreviation = getAbbreviation(text);

    if (!abbreviation.isPresent()) {
        return Optional.empty();
    }/*from w w w .  j  a  v a  2s  .  c o m*/

    Abbreviation abbr = abbreviation.get();
    return Optional.of(abbr.getMedlineAbbreviation());
}

From source file:net.sf.jabref.logic.journals.JournalAbbreviationRepository.java

public Optional<String> getIsoAbbreviation(String text) {
    Optional<Abbreviation> abbreviation = getAbbreviation(text);

    if (!abbreviation.isPresent()) {
        return Optional.empty();
    }/*ww w.java  2 s .c  om*/

    Abbreviation abbr = abbreviation.get();
    return Optional.of(abbr.getIsoAbbreviation());
}

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

@Override
public EventEntity findById(String id) {
    try {//  ww w. j  a va 2s  . co  m
        LOGGER.debug("Find event by ID: {}", id);

        Optional<Event> event = eventRepository.findById(id);

        if (event.isPresent()) {
            return convert(event.get());
        }

        throw new EventNotFoundException(id);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to find an event using its ID {}", id, ex);
        throw new TechnicalManagementException(
                "An error occurs while trying to find an event using its ID " + id, ex);
    }
}

From source file:alfio.controller.api.ReservationApiController.java

@RequestMapping(value = "/event/{eventName}/ticket/{ticketIdentifier}/assign", method = RequestMethod.POST, headers = "X-Requested-With=XMLHttpRequest")
public Map<String, Object> assignTicketToPerson(@PathVariable("eventName") String eventName,
        @PathVariable("ticketIdentifier") String ticketIdentifier,
        @RequestParam(value = "single-ticket", required = false, defaultValue = "false") boolean singleTicket,
        UpdateTicketOwnerForm updateTicketOwner, BindingResult bindingResult, HttpServletRequest request,
        Model model, Authentication authentication) throws Exception {

    Optional<UserDetails> userDetails = Optional.ofNullable(authentication).map(Authentication::getPrincipal)
            .filter(UserDetails.class::isInstance).map(UserDetails.class::cast);

    Optional<Triple<ValidationResult, Event, Ticket>> assignmentResult = ticketHelper.assignTicket(eventName,
            ticketIdentifier, updateTicketOwner, Optional.of(bindingResult), request, t -> {
                Locale requestLocale = RequestContextUtils.getLocale(request);
                model.addAttribute("ticketFieldConfiguration",
                        ticketHelper.findTicketFieldConfigurationAndValue(t.getMiddle().getId(), t.getRight(),
                                requestLocale));
                model.addAttribute("value", t.getRight());
                model.addAttribute("validationResult", t.getLeft());
                model.addAttribute("countries", TicketHelper.getLocalizedCountries(requestLocale));
                model.addAttribute("event", t.getMiddle());
                model.addAttribute("useFirstAndLastName", t.getMiddle().mustUseFirstAndLastName());
                model.addAttribute("availableLanguages", i18nManager.getEventLanguages(eventName).stream()
                        .map(ContentLanguage.toLanguage(requestLocale)).collect(Collectors.toList()));
                String uuid = t.getRight().getUuid();
                model.addAttribute("urlSuffix", singleTicket ? "ticket/" + uuid + "/view" : uuid);
                model.addAttribute("elementNamePrefix", "");
            }, userDetails);/*  w  ww. ja  v a 2  s  .  c o m*/
    Map<String, Object> result = new HashMap<>();

    Optional<ValidationResult> validationResult = assignmentResult.map(Triple::getLeft);
    if (validationResult.isPresent() && validationResult.get().isSuccess()) {
        result.put("partial",
                templateManager.renderServletContextResource("/WEB-INF/templates/event/assign-ticket-result.ms",
                        model.asMap(), request, TemplateManager.TemplateOutput.HTML));
    }
    result.put("validationResult", validationResult.orElse(
            ValidationResult.failed(new ValidationResult.ErrorDescriptor("fullName", "error.fullname"))));
    return result;
}

From source file:org.jhk.pulsing.web.service.prod.PulseService.java

@Override
public Result<Pulse> getPulse(PulseId pulseId) {
    Optional<Pulse> optPulse = redisPulseDao.getPulse(pulseId);

    return optPulse.isPresent() ? new Result<>(SUCCESS, optPulse.get())
            : new Result<>(FAILURE, "Unabled to find " + pulseId);
}