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.devicehive.service.configuration.ConfigurationService.java

@Transactional
public <T> void save(@NotNull String name, T value) {
    //TODO check keys are same
    String str = value != null ? value.toString() : null;
    Optional<ConfigurationVO> existingOpt = findByName(name);
    if (existingOpt.isPresent()) {
        ConfigurationVO existing = existingOpt.get();
        existing.setValue(str);//  w w w  .j av  a  2  s  .  c  o  m
        configurationDao.merge(existing);
    } else {
        ConfigurationVO configuration = new ConfigurationVO();
        configuration.setName(name);
        configuration.setValue(str);
        configurationDao.persist(configuration);
    }
}

From source file:com.linksinnovation.elearning.controller.api.ViewerController.java

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public void get(@PathVariable("id") Long id, @AuthenticationPrincipal String username) {
    Lecture lecture = lectureRepository.findOne(id);
    UserDetails userDetails = userDetailsRepository.findOne(username);
    Optional<Viewer> viOptional = viewerRepository.findByLectureAndUser(lecture, userDetails);
    Viewer viewer;/*from   w  w  w. j  a v  a 2s  . c  o m*/
    if (viOptional.isPresent()) {
        viewer = viOptional.get();
        viewer.setUpdateDate(new Date());
    } else {
        viewer = new Viewer();
        viewer.setLecture(lecture);
        viewer.setUser(userDetails);
        viewer.setUpdateDate(new Date());
    }
    viewerRepository.save(viewer);
}

From source file:alfio.manager.EventNameManager.java

/**
 * Generates and returns a short name based on the given display name.<br>
 * The generated short name will be returned only if it was not already used.<br>
 * The input parameter will be clean from "evil" characters such as punctuation and accents
 *
 * 1) if the {@code displayName} is a one-word name, then no further calculation will be done and it will be returned as it is, to lower case
 * 2) the {@code displayName} will be split by word and transformed to lower case. If the total length is less than 15, then it will be joined using "-" and returned
 * 3) the first letter of each word will be taken, excluding numbers
 * 4) a random code will be returned//from w  ww  .j av a 2 s  .  c  om
 *
 * @param displayName
 * @return
 */
public String generateShortName(String displayName) {
    Validate.isTrue(StringUtils.isNotBlank(displayName));
    String cleanDisplayName = StringUtils.stripAccents(StringUtils.normalizeSpace(displayName))
            .toLowerCase(Locale.ENGLISH).replaceAll(FIND_EVIL_CHARACTERS, "-");
    if (!StringUtils.containsWhitespace(cleanDisplayName) && isUnique(cleanDisplayName)) {
        return cleanDisplayName;
    }
    Optional<String> dashedName = getDashedName(cleanDisplayName);
    if (dashedName.isPresent()) {
        return dashedName.get();
    }
    Optional<String> croppedName = getCroppedName(cleanDisplayName);
    if (croppedName.isPresent()) {
        return croppedName.get();
    }
    return generateRandomName();
}

From source file:com.fredhopper.connector.query.populators.response.SearchResponseFacetsPopulator.java

@Override
public void populate(final FhSearchResponse source, final FacetSearchPageData<FhSearchQueryData, I> target)
        throws ConversionException {
    final Optional<Universe> universe = getUniverse(source);
    if (universe.isPresent() && CollectionUtils.isNotEmpty(universe.get().getFacetmap())) {
        final Results results = universe.get().getItemsSection().getResults();
        final int totalNumberResults = results != null ? results.getTotalItems() : 1;
        final List<Facetmap> facetMap = universe.get().getFacetmap();
        final List<FacetData<FhSearchQueryData>> facets = new ArrayList<>();
        for (final Facetmap facet : facetMap) {
            final List<Filter> filters = facet.getFilter();
            for (final Filter filter : filters) {
                final FacetData<FhSearchQueryData> facetData = createFacetData(source, filter,
                        totalNumberResults);
                facets.add(facetData);/*from   ww  w  . j av a2  s .co  m*/
            }
        }
        target.setFacets(facets);
    } else {
        target.setFacets(Collections.emptyList());
    }
}

From source file:io.dfox.junit.http.example.NoteServlet.java

@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    addBasicHeaders(response);/*from  w  w  w .j  a  v  a2 s  .c  om*/

    String name = getNoteName(request);

    Optional<InputStream> note = repository.getNote(name);
    if (note.isPresent()) {
        try (InputStream noteStream = note.get()) {
            try (OutputStream outputStream = response.getOutputStream()) {
                IOUtils.copy(noteStream, outputStream);
            }
        }
    } else {
        response.setStatus(404);
    }
}

From source file:net.sf.jabref.logic.fetcher.DoiResolution.java

@Override
public Optional<URL> findFullText(BibEntry entry) throws IOException {
    Objects.requireNonNull(entry);
    Optional<URL> pdfLink = Optional.empty();

    Optional<DOI> doi = DOI.build(entry.getField("doi"));

    if (doi.isPresent()) {
        String sciLink = doi.get().getURLAsASCIIString();

        // follow all redirects and scan for a single pdf link
        if (!sciLink.isEmpty()) {
            try {
                Connection connection = Jsoup.connect(sciLink);
                connection.followRedirects(true);
                connection.ignoreHttpErrors(true);
                // some publishers are quite slow (default is 3s)
                connection.timeout(5000);

                Document html = connection.get();
                // scan for PDF
                Elements elements = html.body().select("[href]");
                List<Optional<URL>> links = new ArrayList<>();

                for (Element element : elements) {
                    String href = element.attr("abs:href");
                    // Only check if pdf is included in the link
                    // See https://github.com/lehner/LocalCopy for scrape ideas
                    if (href.contains("pdf") && MimeTypeDetector.isPdfContentType(href)) {
                        links.add(Optional.of(new URL(href)));
                    }//from  w ww.j ava2s  .  c o m
                }
                // return if only one link was found (high accuracy)
                if (links.size() == 1) {
                    LOGGER.info("Fulltext PDF found @ " + sciLink);
                    pdfLink = links.get(0);
                }
            } catch (IOException e) {
                LOGGER.warn("DoiResolution fetcher failed: ", e);
            }
        }
    }
    return pdfLink;
}

From source file:org.openmhealth.shim.fitbit.mapper.FitbitStepCountDataPointMapper.java

@Override
protected Optional<DataPoint<StepCount>> asDataPoint(JsonNode node) {

    int stepCountValue = Integer.parseInt(asRequiredString(node, "value"));

    if (stepCountValue == 0) {
        return Optional.empty();
    }/*from  w  w w .  j a v  a 2s  .com*/

    StepCount.Builder builder = new StepCount.Builder(stepCountValue);

    Optional<LocalDate> stepDate = asOptionalLocalDate(node, "dateTime");

    if (stepDate.isPresent()) {
        LocalDateTime startDateTime = stepDate.get().atTime(0, 0, 0, 0);

        builder.setEffectiveTimeFrame(TimeInterval.ofStartDateTimeAndDuration(
                combineDateTimeAndTimezone(startDateTime), new DurationUnitValue(DAY, 1)));
    }

    StepCount measure = builder.build();
    Optional<Long> externalId = asOptionalLong(node, "logId");

    return Optional.of(newDataPoint(measure, externalId.orElse(null)));
}

From source file:com.teradata.benchto.driver.execution.ExecutionDriver.java

private boolean isTimeLimitEnded() {
    Optional<Duration> timeLimit = properties.getTimeLimit();
    return timeLimit.isPresent() && timeLimit.get().compareTo(Duration.between(startTime, nowUtc())) < 0;
}

From source file:me.adaptive.core.data.api.WorkspaceMemberService.java

public WorkspaceMemberEntity toWorkspaceMemberEntity(Member member,
        Optional<WorkspaceMemberEntity> workspaceMemberEntity) {
    WorkspaceMemberEntity entity = workspaceMemberEntity.isPresent() ? workspaceMemberEntity.get()
            : new WorkspaceMemberEntity();
    CollectionUtils.addAll(entity.getRoles(), member.getRoles().iterator());
    entity.setUser(member.getUserId() == null ? null : userService.findByUserId(member.getUserId()).get());
    entity.setWorkspace(member.getWorkspaceId() == null ? null
            : workspaceEntityService.findByWorkspaceId(member.getWorkspaceId()).get());
    return entity;
}

From source file:com.ebay.logstorm.server.services.impl.PipelineEntityServiceImpl.java

@Override
public PipelineEntity getPipelineByIdOrThrow(String uuid) throws Exception {
    Optional<PipelineEntity> entity = getPipelineByUuid(uuid);
    if (entity.isPresent()) {
        return entity.get();
    } else {//  w  w  w  .j a  v  a2 s.c  o  m
        throw new PipelineException("Pipeline [uuid='" + uuid + "'] not found");
    }
}