Example usage for java.util Optional orElseThrow

List of usage examples for java.util Optional orElseThrow

Introduction

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

Prototype

public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X 

Source Link

Document

If a value is present, returns the value, otherwise throws an exception produced by the exception supplying function.

Usage

From source file:com.largecode.interview.rustem.service.UsersServiceImpl.java

@Override
public void updateUser(Long id, UserDto userDto, Role roleOfCreator) {
    LOGGER.debug("Update user id = {} with data {}", id, userDto);
    Optional<User> userInDb = Optional.ofNullable(userRepository.findOne(id));
    userInDb.ifPresent((user) -> {//from w  w w .  j  av a2s .c  o  m
        roleOfCreator.modifyUserProperties(userDto, user);
        userRepository.saveAndFlush(user);
    });
    userInDb.orElseThrow(
            () -> new NoSuchElementException(String.format("User=%s not found for updating.", id)));

}

From source file:ee.ria.xroad.opmonitordaemon.HealthDataRequestHandler.java

@SuppressWarnings("unchecked")
private JAXBElement<?> buildHealthDataResponse(Optional<ClientId> provider) throws Exception {
    GetSecurityServerHealthDataResponseType healthDataResponse = OBJECT_FACTORY
            .createGetSecurityServerHealthDataResponseType();

    Optional<Gauge<Long>> timestamp = Optional
            .ofNullable(findGauge(healthMetricRegistry, MONITORING_STARTUP_TIMESTAMP));

    healthDataResponse.setMonitoringStartupTimestamp(timestamp.orElseThrow(this::missingTimestamp).getValue());
    Optional<Gauge<Integer>> statisticsPeriodSeconds = Optional
            .ofNullable(findGauge(healthMetricRegistry, STATISTICS_PERIOD_SECONDS));
    healthDataResponse/*from  ww  w.  ja  v a  2  s .co  m*/
            .setStatisticsPeriodSeconds(statisticsPeriodSeconds.orElseThrow(this::missingPeriod).getValue());

    healthDataResponse.setServicesEvents(buildServicesEvents(provider));

    return OBJECT_FACTORY.createGetSecurityServerHealthDataResponse(healthDataResponse);
}

From source file:ch.wisv.areafiftylan.integration.RFIDIntegrationTest.java

@Test
public void testAddRFIDLinkAsAdmin() {
    User admin = createAdmin();//from   w ww  .ja v a2  s.  c  o  m
    Ticket ticket = createTicketForUser(admin);
    RFIDLinkDTO dto = createRFIDLinkDTO(ticket);

    //@formatter:off
    given().header(getXAuthTokenHeaderForUser(admin)).when().body(dto).contentType(ContentType.JSON)
            .post(RFID_ENDPOINT).then().statusCode(HttpStatus.SC_OK);
    //@formatter:on

    Optional<RFIDLink> queryResult = rfidLinkRepository.findByRfid(dto.getRfid());
    Assert.assertEquals(queryResult.orElseThrow(RFIDNotFoundException::new).getTicket().getId(),
            ticket.getId());
}

From source file:nu.yona.server.subscriptions.rest.BuddyController.java

private GoalDto getGoal(UUID userId, UUID buddyId, UUID goalId) {
    BuddyDto buddy = buddyService.getBuddy(buddyId);
    Optional<GoalDto> goal = buddy.getGoals().orElse(Collections.emptySet()).stream()
            .filter(g -> g.getGoalId().equals(goalId)).findAny();
    return goal.orElseThrow(() -> GoalServiceException.goalNotFoundByIdForBuddy(userId, buddyId, goalId));
}

From source file:com.vsct.dt.strowgr.admin.gui.resource.api.EntrypointResources.java

@GET
@Path("/{id : .+}/current")
@Timed/*from   ww w  .  j  a  va2 s .co m*/
public EntryPointMappingJson getCurrent(@PathParam("id") String id) throws JsonProcessingException {
    Optional<EntryPoint> configuration = repository.getCurrentConfiguration(new EntryPointKeyDefaultImpl(id));

    return new EntryPointMappingJson(configuration.orElseThrow(NotFoundException::new));
}

From source file:com.vsct.dt.strowgr.admin.gui.resource.api.EntrypointResources.java

@GET
@Path("/{id : .+}/pending")
@Timed/*from ww w  . j  a v a 2s  .c  o  m*/
public EntryPointMappingJson getPending(@PathParam("id") String id) throws JsonProcessingException {
    Optional<EntryPoint> configuration = repository.getPendingConfiguration(new EntryPointKeyDefaultImpl(id));

    return new EntryPointMappingJson(configuration.orElseThrow(NotFoundException::new));
}

From source file:com.vsct.dt.strowgr.admin.gui.resource.api.EntrypointResources.java

@GET
@Path("/{id : .+}/committing")
@Timed/*from  w ww .j  a v  a  2  s.  c  o m*/
public EntryPointMappingJson getCommitting(@PathParam("id") String id) throws JsonProcessingException {
    Optional<EntryPoint> configuration = repository
            .getCommittingConfiguration(new EntryPointKeyDefaultImpl(id));

    return new EntryPointMappingJson(configuration.orElseThrow(NotFoundException::new));
}

From source file:com.uber.hoodie.hive.HoodieHiveClient.java

/**
 * Read schema from a data file from the last compaction commit done.
 *
 * @param lastCompactionCommitOpt//  w ww.  j  a v  a 2 s.c o  m
 * @return
 * @throws IOException
 */
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private MessageType readSchemaFromLastCompaction(Optional<HoodieInstant> lastCompactionCommitOpt)
        throws IOException {
    HoodieInstant lastCompactionCommit = lastCompactionCommitOpt.orElseThrow(() -> new HoodieHiveSyncException(
            "Could not read schema from last compaction, no compaction commits found on path "
                    + syncConfig.basePath));

    // Read from the compacted file wrote
    HoodieCompactionMetadata compactionMetadata = HoodieCompactionMetadata
            .fromBytes(activeTimeline.getInstantDetails(lastCompactionCommit).get());
    String filePath = compactionMetadata.getFileIdAndFullPaths(metaClient.getBasePath()).values().stream()
            .findAny()
            .orElseThrow(() -> new IllegalArgumentException(
                    "Could not find any data file written for compaction " + lastCompactionCommit
                            + ", could not get schema for dataset " + metaClient.getBasePath()));
    return readSchemaFromDataFile(new Path(filePath));
}

From source file:com.appdirect.connector.autodesk.service.AutodeskServiceImpl.java

protected String getSubscriptionId(String poNumber, String contractNumber, String productName)
        throws AutodeskServiceException, AutodeskAPIException {
    String initialSku = getSku(productName, OperationType.INITIAL_ORDER);
    OrderDetailsResponse orderDetails = getOrderDetails(poNumber);

    Optional<OrderItemsArray> itemOptional = orderDetails.getMessage().getElements().stream()
            .filter(element -> element.getOrderHeaderArray().stream()
                    .filter(h -> h.getContractNumber().equals(contractNumber)).findFirst().isPresent())
            .findFirst().map(element -> element.getOrderItemsArray()).orElse(Collections.emptyList()).stream()
            .filter(item -> item.getSku().equals(initialSku) && item.getSalesLicenseType().equals(NEW))
            .findFirst();/*from  w w  w . j ava 2  s. c om*/

    return itemOptional.orElseThrow(
            () -> new AutodeskServiceException(String.format(SUBS_ID_NOT_FOUND_MESSAGE, poNumber, productName)))
            .getSubsId();
}