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:io.redlink.solrlib.SolrCoreDescriptor.java

@SuppressWarnings("squid:S3725")
static void unpackSolrCoreDir(Path solrCoreBundle, Path solrCoreDir) throws IOException {
    LoggerFactory.getLogger(SolrCoreDescriptor.class).debug("Unpacking SolrCore directory {} to {}",
            solrCoreBundle, solrCoreDir);
    try (Stream<Path> pathStream = Files.find(solrCoreBundle, Integer.MAX_VALUE,
            (p, a) -> Files.isRegularFile(p) && Files.isReadable(p)
                    && "core.properties".equals(String.valueOf(p.getFileName())))) {
        final Optional<Path> coreProperties = pathStream.min(Comparator.comparingInt(Path::getNameCount));
        final Path sourceDir = coreProperties
                .orElseThrow(() -> new IllegalArgumentException(
                        "Invalid solrCoreBundle '" + solrCoreBundle + "': no core.properties found"))
                .getParent();//from w  ww.  j a  v a2  s .c o m

        PathUtils.copyRecursive(sourceDir, solrCoreDir);
    }
}

From source file:com.netflix.spinnaker.halyard.core.registry.v1.BillOfMaterials.java

static private <T> String getFieldVersion(Class<T> clazz, T obj, String artifactName) {
    Optional<Field> field = Arrays.stream(clazz.getDeclaredFields()).filter(f -> {
        boolean nameMatches = f.getName().equals(artifactName);
        boolean propertyMatches = false;
        JsonProperty property = f.getDeclaredAnnotation(JsonProperty.class);
        if (property != null) {
            propertyMatches = property.value().equals(artifactName);
        }//from   www  . j a  va  2 s.  c om
        return nameMatches || propertyMatches;
    }).findFirst();

    try {
        return ((Artifact) field.orElseThrow(() -> new NoKnownArtifact(artifactName)).get(obj)).getVersion();
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (NullPointerException e) {
        throw new RuntimeException("Versioned artifact " + artifactName + " is not listed in the BOM");
    }
}

From source file:io.pravega.controller.store.stream.tables.TableHelper.java

/**
 * Return segments in the epoch./*from   w  w  w .  ja  va 2 s .co m*/
 * @param historyTableData history table
 * @param epoch            epoch
 *
 * @return segments in the epoch
 */
public static List<Integer> getSegmentsInEpoch(byte[] historyTableData, int epoch) {
    Optional<HistoryRecord> record = HistoryRecord.readLatestRecord(historyTableData, false);

    while (record.isPresent() && record.get().getEpoch() > epoch) {
        record = HistoryRecord.fetchPrevious(record.get(), historyTableData);
    }

    return record.orElseThrow(() -> StoreException.create(StoreException.Type.DATA_NOT_FOUND,
            "Epoch: " + epoch + " not found in history table")).getSegments();
}

From source file:th.co.geniustree.intenship.advisor.service.MyUserDetailService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Optional<Account> findByEmail = accountRepo.findByEmail(username);
    return findByEmail.orElseThrow(() -> new UsernameNotFoundException("not found user."));
}

From source file:pl.java.scalatech.audit.SpringSecurityAuditorAware.java

@Override
public User getCurrentAuditor() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String login = ANONYMOUS;//from  w w  w  . jav  a  2  s .c  om
    if (auth != null) {
        login = auth.getName();
    }
    log.info("+++++++++++++++++++ +++++++++++++++++++++++++++++ login from security context : {}", login);
    Optional<User> user = userRepository.findByLogin(login);
    User loaded = user.orElseThrow(() -> new IllegalArgumentException("user not exists"));
    log.info("+++++++++++++++++  +++++++++++++++++++++++++++++  {}", loaded);
    return loaded;
}

From source file:io.github.carlomicieli.footballdb.starter.pages.TableBuilderTests.java

@Test
public void shouldBuildNewTablesFromElements() {
    Optional<Table> table = TableBuilder.fromElement(tableElement());

    Table tab = table.orElseThrow(RuntimeException::new);

    assertThat(tab.size()).isEqualTo(ImmutablePair.of(3, 3));
    assertThat(tab.rowValues(1)).contains(Arrays.asList("1", "one", "3"));
    assertThat(tab.rowValues(2)).contains(Arrays.asList("", "", ""));
    assertThat(tab.rowValues(3)).contains(Arrays.asList("2", "two", "1"));
}

From source file:com.unidev.polycms.hateoas.controller.StorageQueryController.java

@GetMapping(value = "/storage/{storage}/poly/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public HateoasResponse fetchPoly(@PathVariable("storage") String storage, @PathVariable("id") String id) {
    if (!polyCore.existTenant(storage)) {
        LOG.warn("Not found storage {}", storage);
        throw new StorageNotFoundException("Storage " + storage + " not found");
    }/*from   w  ww.  j  av  a2s .  co  m*/
    SQLitePolyStorage sqLitePolyStorage = polyCore.fetchSqliteStorage(storage);

    Optional<PolyRecord> polyRecord = sqLitePolyStorage.fetchPoly(id);
    polyRecord.orElseThrow(StorageNotFoundException::new);
    HateoasResponse hateoasResponse = hateoasResponse().data(polyRecord.get());
    hateoasResponse.add(linkTo(StorageIndexController.class).slash("storage").slash(storage).slash("poly")
            .slash(id).withSelfRel());
    return hateoasResponse;
}

From source file:org.openwms.common.location.LocationGroupController.java

@RequestMapping(value = CommonConstants.API_LOCATIONGROUPS, method = RequestMethod.GET, params = { "name" })
public LocationGroupVO getLocationGroup(@RequestParam("name") String name) {
    Optional<LocationGroup> opt = locationGroupService.findByName(name);
    LocationGroup locationGroup = opt.orElseThrow(() -> new NotFoundException(translator,
            CommonMessageCodes.LOCATION_GROUP_NOT_FOUND, new String[] { name }, name));
    LocationGroupVO result = mapper.map(locationGroup, LocationGroupVO.class);
    if (locationGroup.hasParent()) {
        result.add(linkTo(// www .  j av  a 2  s. c  om
                methodOn(LocationGroupController.class).getLocationGroup(locationGroup.getParent().getName()))
                        .withRel("_parent"));
    }
    return result;
}

From source file:com.dickthedeployer.dick.web.service.GroupService.java

public GroupModel getGroup(String name) throws NotFoundException {
    Optional<Group> groupOptional = groupDao.findByNamespaceName(name);
    Group group = groupOptional.orElseThrow(NotFoundException::new);
    List<ProjectModel> projectModels = group.getNamespace().getProjects().stream().map((Project project) -> {
        ProjectModel model = ProjectMapper.mapProjectView(project);
        model.setLastBuild(buildService.findLastBuild(project));
        return model;
    }).collect(toList());/*from   w w w  .  j  a  v a  2s.c  o m*/
    GroupModel model = GroupMapper.mapGroupShallow(group);
    Collections.reverse(projectModels);
    model.setProjects(projectModels);
    return model;
}

From source file:com.dickthedeployer.dick.web.service.WorkerService.java

@Transactional
public void deleteWorker(String name) throws NotFoundException, WorkerBusyException {
    Optional<Worker> workerOptional = workerDao.findByName(name);
    Worker worker = workerOptional.orElseThrow(NotFoundException::new);
    Long assigned = jobBuildDao.countByWorker(worker);
    if (assigned != 0) {
        throw new WorkerBusyException();
    }/* w w w  .j  a v  a 2 s  . c  o  m*/
    workerDao.delete(worker);
}