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.github.lukaszbudnik.dqueue.QueueClientIntegrationTest.java

@Test
public void shouldPublishAndConsumeWithoutFilters() throws ExecutionException, InterruptedException {
    UUID startTime = UUIDs.timeBased();
    String name = "name 1";
    ByteBuffer contents = ByteBuffer.wrap(name.getBytes());

    Future<UUID> publishFuture = queueClient.publish(new Item(startTime, contents));
    publishFuture.get();//  w w  w . ja va 2s  .c  om

    Future<Optional<Item>> itemFuture = queueClient.consume();

    Optional<Item> item = itemFuture.get();

    UUID consumedStartTime = item.get().getStartTime();
    ByteBuffer consumedContents = item.get().getContents();

    assertEquals(startTime, consumedStartTime);
    assertEquals(contents, consumedContents);
}

From source file:ddf.catalog.validation.impl.validator.RequiredAttributesMetacardValidator.java

@Override
public void validate(final Metacard metacard) throws ValidationException {
    final Optional<MetacardValidationReport> reportOptional = validateMetacard(metacard);

    if (reportOptional.isPresent()) {
        final List<String> errors = reportOptional.get().getMetacardValidationViolations().stream()
                .map(ValidationViolation::getMessage).collect(Collectors.toList());

        final ValidationExceptionImpl exception = new ValidationExceptionImpl();
        exception.setErrors(errors);/*from ww w  . ja  v a 2 s  . co  m*/
        throw exception;
    }
}

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

@GET
@Path("/form")
public U get(@Context UriInfo uriInfo, @QueryParam("locale") String locale) {

    Optional<T> optionalConfig = getConfigService().findComplete();

    if (!optionalConfig.isPresent())
        throw NoSuchEntityException.withPath(EntityConfig.class, uriInfo.getPath());

    T config = optionalConfig.get();
    entityConfigTranslator.translateSchemaForm(locale, config);

    return asDto(config);
}

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

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

    // Try unique DOI first
    Optional<DOI> doi = DOI.build(entry.getField("doi"));

    if (doi.isPresent()) {
        // Available in catalog?
        try {/*w ww. j a  v a2 s. c  o m*/
            String sciLink = getUrlByDoi(doi.get().getDOI());

            if (!sciLink.isEmpty()) {
                // Retrieve PDF link
                Document html = Jsoup.connect(sciLink).ignoreHttpErrors(true).get();
                Element link = html.getElementById("pdfLink");

                if (link != null) {
                    LOGGER.info("Fulltext PDF found @ ScienceDirect.");
                    pdfLink = Optional.of(new URL(link.attr("pdfurl")));
                }
            }
        } catch (UnirestException e) {
            LOGGER.warn("ScienceDirect API request failed", e);
        }
    }
    return pdfLink;
}

From source file:spring.travel.site.services.WeatherServiceTest.java

@Test
public void shouldGetDailyForecast() throws Exception {
    stubWeatherData("/weather?id=2652546&cnt=3&mode=json", "/weather-lhr-3days.json");

    HandOff<Optional<DailyForecast>> handOff = new HandOff<>();

    Location location = new Location(2652546, -2.43, 34.66);
    weatherService.forecast(location, 3).whenComplete((df, t) -> handOff.put(df));

    Optional<DailyForecast> dailyForecastOptional = handOff.get(1);

    assertNotEquals(Optional.empty(), dailyForecastOptional);

    DailyForecast dailyForecast = dailyForecastOptional.get();
    assertEquals("Colnbrook", dailyForecast.getCity().getName());
    assertEquals("GB", dailyForecast.getCity().getCountry());

    assertEquals(3, dailyForecast.getForecasts().size());
    List<Forecast> forecasts = dailyForecast.getForecasts();
    Forecast forecast = forecasts.get(0);

    assertEquals(new BigDecimal("285.14"), forecast.getTemperatures().getMin());
    assertEquals(new BigDecimal("295.07"), forecast.getTemperatures().getMax());
}

From source file:com.intel.podm.client.typeidresolver.ResourceResolver.java

@Override
public JavaType typeFromId(DatabindContext context, String id) {
    for (OdataTypeMatcher matcher : MATCHERS) {
        Optional<Class> matchedClass = matcher.match(id);

        if (matchedClass.isPresent()) {
            return defaultInstance().constructSpecializedType(baseType, matchedClass.get());
        }/*from  ww  w .  j a  v a 2 s .  c  o m*/
    }

    if (defaultTypeRequired()) {
        return createDefaultType(id);
    }

    LOGGER.e("Encountered an unknown @odata.type: {}", id);
    throw new NotImplementedException(id);
}

From source file:com.github.cbismuth.fdupes.io.PathOrganizer.java

private void moveUniqueFiles(final Path destination, final Iterable<PathElement> uniqueElements) {
    final AtomicInteger counter = new AtomicInteger(1);

    uniqueElements.forEach(pathElement -> {
        final Optional<Path> timestampPath = pathAnalyser.getTimestampPath(destination, pathElement.getPath());

        if (timestampPath.isPresent()) {
            onTimestampPath(pathElement, timestampPath.get());
        } else {/* w ww .  jav a2s.  c  o  m*/
            onNoTimestampPath(destination, pathElement, counter);
        }
    });
}

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

@RequestMapping(value = "/check/{courseId}", method = RequestMethod.POST)
public List<ResultDTO> check(@PathVariable("courseId") Long courseId, @RequestBody List<AnswerDTO> answerDTOs,
        @AuthenticationPrincipal String username) {
    List<ResultDTO> resultDTOs = new ArrayList<>();
    UserDetails userDetails = userDetailsRepository.findOne(username);
    Course course = courseRepositroy.findOne(courseId);
    int count = 0;
    for (AnswerDTO answerDTO : answerDTOs) {
        Quiz quiz = quizRepository.findOne(answerDTO.getQuiz());
        Answer answer = answerRepository.findOne(answerDTO.getAnswer());
        ResultDTO resultDTO = new ResultDTO(quiz.getQuestion(), answer.getAnswer(), answer.isChecked());
        if (answer.isChecked()) {
            count++;/*  www .ja v  a  2  s.c  om*/
        }
        resultDTOs.add(resultDTO);
    }
    Optional<QuizScore> qs = quizScoreRepository.findByUserAndCourse(userDetails, course);
    QuizScore quizScore;
    if (qs.isPresent()) {
        quizScore = qs.get();
    } else {
        quizScore = new QuizScore();
    }
    quizScore.setPass(count);
    quizScore.setTotal(resultDTOs.size());
    quizScore.setUser(userDetails);
    quizScore.setCourse(course);
    quizScore.setUpdateDate(new Date());
    quizScoreRepository.save(quizScore);
    return resultDTOs;
}

From source file:com.watchrabbit.scanner.generator.service.GeneratorServiceImpl.java

@Override
public FieldValue generateValue(List<String> descriptions, List<String> words) {
    if (emailGenerator.accepts(descriptions)) {
        return emailGenerator.generate(descriptions, words);
    }/*ww  w.  j a v a2  s .c om*/
    if (urlGenerator.accepts(descriptions)) {
        return urlGenerator.generate(descriptions, words);
    }
    if (passwordGenerator.accepts(descriptions)) {
        return passwordGenerator.generate(descriptions, words);
    }

    Optional<ValueGenerator> optionalGenerator = valueGenerators.stream()
            .filter(generator -> generator.accepts(descriptions)).findFirst();
    if (optionalGenerator.isPresent()) {
        return optionalGenerator.get().generate(descriptions, words);
    }

    return fallbackGenerator.generate(descriptions, words);
}

From source file:io.gravitee.gateway.env.GatewayConfigurationTest.java

@Test
public void shouldReturnTenantWithPrecedence() {
    System.setProperty(GatewayConfiguration.MULTI_TENANT_SYSTEM_PROPERTY, "asia");
    Mockito.when(environment.getProperty(GatewayConfiguration.MULTI_TENANT_CONFIGURATION)).thenReturn("europe");
    gatewayConfiguration.afterPropertiesSet();

    Optional<String> tenantOpt = gatewayConfiguration.tenant();
    Assert.assertTrue(tenantOpt.isPresent());

    Assert.assertEquals("asia", tenantOpt.get());
}