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:lumbermill.internal.StringTemplateTest.java

@Test
public void testExtractSingleValue() {
    StringTemplate t = StringTemplate.compile("{field}");
    JsonEvent event = Codecs.TEXT_TO_JSON.from("Hello").put("field", "value");
    Optional<String> formattedString = t.format(event);
    assertThat(formattedString.isPresent()).isTrue();
    assertThat(formattedString.get()).isEqualTo("value");
}

From source file:com.epam.ta.reportportal.core.externalsystem.StrategyProvider.java

/**
 * Validate external system name and provide strategy for interacting with
 * external system./*from   w  ww .j  av  a  2  s . c  o  m*/
 *
 * @param externalSystemName Name of external system
 * @return
 */
public ExternalSystemStrategy getStrategy(String externalSystemName) {
    Optional<ExternalSystemType> externalSystem = ExternalSystemType.findByName(externalSystemName);
    validate(externalSystem, externalSystemName);
    externalSystemStrategy.checkAvailable(externalSystem.get());
    return externalSystemStrategy;
}

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

@RequestMapping(value = "/score/{courseId}", method = RequestMethod.GET)
public QuizScore getScore(@PathVariable("courseId") Long courseId, @AuthenticationPrincipal String username) {
    UserDetails userDetails = userDetailsRepository.findOne(username);
    Course course = courseRepositroy.findOne(courseId);
    Optional<QuizScore> quizscore = quizScoreRepository.findByUserAndCourse(userDetails, course);
    if (quizscore.isPresent()) {
        return quizscore.get();
    } else {/*from  w  w  w . j  a v a2  s .  c o m*/
        return null;
    }
}

From source file:com.blackducksoftware.integration.hub.detect.detector.gradle.GradleReportParserTest.java

private DetectCodeLocation build(final String resource) throws IOException {
    final File file = new File(resource);
    final GradleReportParser gradleReportParser = new GradleReportParser(new ExternalIdFactory());
    final Optional<DetectCodeLocation> result = gradleReportParser.parseDependencies(file);
    if (result.isPresent()) {
        return result.get();
    } else {/*w ww .  j  av a2  s.co  m*/
        return null;
    }
}

From source file:com.fredhopper.connector.index.populator.CategoryPopulator.java

@Override
public void populate(final ItemToConvert<CategoryModel> source, final FhCategoryData target)
        throws ConversionException {
    Preconditions.checkArgument(source != null);
    Preconditions.checkArgument(target != null);

    final CategoryModel category = source.getItem();
    final Set<Locale> locales = source.getIndexConfig().getLocales();

    target.setCategoryId(getSanitizeIdStrategy().sanitizeId(category.getCode()));
    target.setNames(mapNames(category, locales));
    final Optional<CategoryModel> parent = parentCategoryResolver.resolve(category);
    if (parent.isPresent()) {
        target.setParentId(getSanitizeIdStrategy().sanitizeId(parent.get().getCode()));
    }/* www . j  av  a 2s .  c  om*/
}

From source file:org.ameba.aop.IntegrationLayerAspect.java

/**
 * Called after an exception is thrown by classes of the integration layer. <p> Set log level to ERROR to log the root cause. </p>
 *
 * @param ex The root exception that is thrown
 * @return Returns the exception to be thrown
 *///from  www  . java2s  . com
public Exception translateException(Exception ex) {
    if (EXC_LOGGER.isErrorEnabled()) {
        EXC_LOGGER.error(ex.getLocalizedMessage(), ex);
    }

    if (ex instanceof BusinessRuntimeException) {
        return ex;
    }

    Optional<Exception> handledException = doTranslateException(ex);
    if (handledException.isPresent()) {
        return handledException.get();
    }
    if (ex instanceof DuplicateKeyException) {
        return new ResourceExistsException();
    }
    if (ex instanceof IntegrationLayerException) {
        return ex;
    }
    return withRootCause ? new IntegrationLayerException(ex.getMessage(), ex)
            : new IntegrationLayerException(ex.getMessage());
}

From source file:things.view.rest.ThingRestController.java

@Transactional(readOnly = true)
@RequestMapping(value = "/{type}/{key}")
@Timed//from   w w w  . j  a  va 2s  . c  o m
public Thing getUniqueThingForTypeAndKey(@PathVariable("type") String type, @PathVariable("key") String key)
        throws ThingException, NoSuchThingException {
    Optional<Thing> thing = thingControl.findUniqueThingMatchingTypeAndKey(type, key, true);

    if (!thing.isPresent()) {
        throw new NoSuchThingException(type, key);
    }

    return thing.get();
}

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

/**
 * //from   ww w  .j a v a  2s.c o  m
 *
 * @param token
 * @param pid
 * @return
 * @throws HttpProvisionRuntimeException If project does not exists.
 */
protected Boolean isValidToken(String token, ProjectInstanceIdentifier pid) {
    CacheKey key = new CacheKey(token, pid);
    return validTokens.get(key, _key -> {
        Project project = uow.get().findProject(pid.organization(), pid.project())
                .orElseThrow(() -> new HttpProvisionRuntimeException(404, "No such project: " + pid));
        Optional<AuthToken> projectToken = project.serviceAuthToken();
        return projectToken.isPresent() ? projectToken.get().isValid(token) : false;
    });
}

From source file:example.springdata.jpa.java8.Java8IntegrationTests.java

@Test
public void invokesDefaultMethod() {

    Customer customer = repository.save(new Customer("Dave", "Matthews"));
    Optional<Customer> result = repository.findByLastname(customer);

    assertThat(result.isPresent(), is(true));
    assertThat(result.get(), is(customer));
}

From source file:com.epam.catgenome.controller.vo.externaldb.NCBIVariationVO.java

@JsonProperty(value = "gene_summary")
public String getGene() {
    List<NCBIShortVarVO.NCBIGeneSummaryVO> genes = ncbiShortVar.getGenes();
    Optional<NCBIShortVarVO.NCBIGeneSummaryVO> first = genes.stream().findFirst();
    return first.isPresent() ? String.format("%s (%s)", first.get().getName(), first.get().getGeneId()) : null;
}