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:net.sf.gazpachoquest.services.core.impl.QuestionnaireServiceImpl.java

@Override
@Transactional(readOnly = false)/*from ww  w  . j a  v  a2s.co  m*/
public QuestionnaireDefinition getDefinition(final Integer questionnaireId) {
    QuestionnaireDefinition example = new QuestionnaireDefinition();
    example.addQuestionnaire(Questionnaire.with().id(questionnaireId).build());
    Optional<QuestionnaireDefinition> definition = questionnaireDefinitionRepository.findOneByExample(example,
            new SearchParameters());
    return definition.orElseThrow(
            () -> new EmptyResultDataAccessException(String.format("No %s entity for {} with id %s found!",
                    QuestionnaireDefinition.class, Questionnaire.class, questionnaireId), 1));
}

From source file:io.syndesis.rest.v1.handler.connection.ConnectionActionHandler.java

public ConnectionActionHandler(final Connection connection, final VerificationConfigurationProperties config) {
    this.connection = connection;
    this.config = config;

    final Optional<Connector> maybeConnector = connection.getConnector();
    connector = maybeConnector.orElseThrow(() -> new EntityNotFoundException(
            "Connection with id `" + connection.getId() + "` does not have a Connector defined"));

    actions = connector.getActions();/*from   www  .j  av  a 2 s .com*/
}

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

@Override
public void deleteUser(Long id) {
    LOGGER.debug("Delete user by id ={}", id);
    Optional<User> userInDb = Optional.ofNullable(userRepository.findOne(id));
    userInDb.ifPresent((user) -> {//from   w  w  w.j ava 2  s.co m
        userRepository.delete(user);
    });
    userInDb.orElseThrow(
            () -> new NoSuchElementException(String.format("User=%s not found for deleting.", id)));

}

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

public ProjectModel getProject(String namespaceName, String name) throws NotFoundException {
    Optional<Project> project = projectDao.findByNamespaceNameAndName(namespaceName, name);
    return mapProject(project.orElseThrow(NotFoundException::new));
}

From source file:com.coinkite.CoinkiteSigningRequestInterceptor.java

protected String getApiSecret() {

    Optional<String> secret = ofNullable(System.getenv(Constants.X_CK_SIGN));

    if (!secret.isPresent()) {
        secret = ofNullable(System.getProperty(Constants.X_CK_SIGN));
    }/*from w ww.  j  a v a  2s .co  m*/

    return secret.orElseThrow(
            () -> new RuntimeException("Coinkite secret was not passed in as a jvm arg or set on env."));
}

From source file:de.speexx.csv.table.app.Application.java

void run(final String... args) throws Exception {
    final Configuration conf = new Configuration();
    final JCommander jc = new JCommander(conf);
    jc.setProgramName(APPLICATION_NAME);
    jc.parse(args);// w w w  .  ja  v a 2  s  .c o  m

    if (conf.isHelp()) {
        jc.usage();
        return;
    }

    final Optional<List<Table>> tables = loadTable(conf);
    final Optional<RowReader> rows = executeQuery(conf,
            tables.orElseThrow(() -> new TableException("No table available")));
    if (rows.isPresent()) {
        exportResult(conf, rows.get());
    }
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.SpinnakerRuntimeSettings.java

private Field getServiceField(String name) {
    String reducedName = name.replace("-", "").replace("_", "");

    Optional<Field> matchingField = Arrays.stream(Services.class.getDeclaredFields())
            .filter(f -> f.getName().equalsIgnoreCase(reducedName)).findFirst();

    return matchingField
            .orElseThrow(() -> new HalException(Problem.Severity.FATAL, "Unknown service " + reducedName));
}

From source file:ddf.catalog.transformer.OverlayMetacardTransformer.java

private BinaryContent overlay(Metacard metacard, Map<String, Serializable> arguments)
        throws CatalogTransformerException {
    final Optional<BufferedImage> bufferedImageOptional = imageSupplier.apply(metacard, arguments);
    final BufferedImage image = bufferedImageOptional.orElseThrow(
            () -> new CatalogTransformerException("Did not receive an image from the image supplier."));

    List<Vector> boundary = parseBoundary(metacard.getLocation());
    BufferedImage tile = createTileFromImageAndBoundary(image, boundary);
    return createBinaryContent(tile);
}

From source file:org.xwiki.contrib.repository.npm.internal.NpmExtensionRepository.java

@Override
public Extension resolve(ExtensionDependency extensionDependency) throws ResolveException {
    String packageName = NpmUtils.getPackageName(extensionDependency.getId());
    IterableResult<Version> versions = resolveVersions(packageName, 0, -1);
    VersionConstraint versionConstraint = extensionDependency.getVersionConstraint();
    Optional<Version> validVersion = getNewestCompatibleVersion(versionConstraint, versions);
    Version version = validVersion.orElseThrow(
            () -> new ExtensionNotFoundException("Could not resolve dependency: [" + packageName + "]"));
    return resolve(new ExtensionId(NpmParameters.DEFAULT_GROUPID + ":" + packageName, version));
}

From source file:com.watchrabbit.scanner.supervisor.service.FormAnalyzerServiceImpl.java

private void locateSendButton(WebElement formElement, Form form) throws InvalidFormStructureException {
    List<WebElement> submit = formElement.findElements(By.xpath(".//button[@type='submit']"));
    if (submit.isEmpty()) {
        submit = formElement.findElements(By.xpath(".//input[@type='submit']"));
    }/*from  w w w .  j av  a  2s.c  o m*/
    if (!submit.isEmpty()) {
        form.setSendButton(submit.get(0));
    } else {
        Optional<WebElement> findAny = formElement.findElements(By.xpath(".//input")).stream()
                .filter(input -> input.isDisplayed()).filter(input -> input.isEnabled()).findAny();
        form.setSendButton(
                findAny.orElseThrow(() -> new InvalidFormStructureException("Cannot locate send button")));
    }
}