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:alfio.model.system.Configuration.java

private static ConfigurationPathKey from(Optional<Integer> organizationId, Optional<Integer> eventId,
        Optional<Integer> ticketCategoryId, ConfigurationKeys key) {
    boolean organizationAvailable = organizationId.isPresent();
    boolean eventAvailable = eventId.isPresent();
    boolean categoryAvailable = ticketCategoryId.isPresent();
    ConfigurationPathLevel mostSensible = Arrays.stream(ConfigurationPathLevel.values())
            .sorted(Comparator.<ConfigurationPathLevel>naturalOrder().reversed()).filter(
                    path -> path == ConfigurationPathLevel.ORGANIZATION && organizationAvailable
                            || path == ConfigurationPathLevel.EVENT && organizationAvailable && eventAvailable
                            || path == ConfigurationPathLevel.TICKET_CATEGORY && organizationAvailable
                                    && eventAvailable && categoryAvailable)
            .findFirst().orElse(ConfigurationPathLevel.SYSTEM);
    switch (mostSensible) {
    case ORGANIZATION:
        return getOrganizationConfiguration(organizationId.get(), key);
    case EVENT:/*from   w ww. j a v a 2 s .  com*/
        return getEventConfiguration(organizationId.get(), eventId.get(), key);
    case TICKET_CATEGORY:
        return getTicketCategoryConfiguration(organizationId.get(), eventId.get(), ticketCategoryId.get(), key);
    }
    return getSystemConfiguration(key);
}

From source file:com.uber.hoodie.common.TestRawTripPayload.java

public TestRawTripPayload(Optional<String> jsonData, String rowKey, String partitionPath, String schemaStr,
        Boolean isDeleted) throws IOException {
    if (jsonData.isPresent()) {
        this.jsonDataCompressed = compressData(jsonData.get());
        this.dataSize = jsonData.get().length();
    }//w  w  w  .  j av  a2  s. com
    this.rowKey = rowKey;
    this.partitionPath = partitionPath;
    this.isDeleted = isDeleted;
}

From source file:io.github.swagger2markup.extensions.DynamicOverviewDocumentExtension.java

@Override
public void init(Swagger2MarkupConverter.Context globalContext) {
    Swagger2MarkupProperties extensionsProperties = globalContext.getConfig().getExtensionsProperties();
    Optional<Path> contentPathProperty = extensionsProperties
            .getPath(extensionId + "." + PROPERTY_CONTENT_PATH);
    if (contentPathProperty.isPresent()) {
        contentPath = contentPathProperty.get();
    } else {/*  w w  w.  j av a2  s.  c om*/
        if (contentPath == null) {
            if (globalContext.getSwaggerLocation() == null
                    || !globalContext.getSwaggerLocation().getScheme().equals("file")) {
                if (logger.isWarnEnabled())
                    logger.warn(
                            "Disable > DynamicOverviewContentExtension > Can't set default contentPath from swaggerLocation. You have to explicitly configure the content path.");
            } else {
                contentPath = Paths.get(globalContext.getSwaggerLocation()).getParent();
            }
        }
    }
    Optional<MarkupLanguage> extensionMarkupLanguageProperty = extensionsProperties
            .getMarkupLanguage(extensionId + "." + PROPERTY_MARKUP_LANGUAGE);
    if (extensionMarkupLanguageProperty.isPresent()) {
        extensionMarkupLanguage = extensionMarkupLanguageProperty.get();
    }
}

From source file:com.bekwam.resignator.PasswordController.java

@FXML
public void resetDataFile(ActionEvent evt) {

    if (logger.isDebugEnabled()) {
        logger.debug("[RESET DATA FILE]");
    }/*ww  w.j  a  va2  s. c  o m*/

    ((Hyperlink) evt.getSource()).getScene().getWindow().hide();

    ButtonType myCancel = new ButtonType("Just Exit", ButtonBar.ButtonData.CANCEL_CLOSE);

    Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Delete all data and exit the app?", ButtonType.OK,
            myCancel);

    alert.setHeaderText("Delete all data");
    //alert.setOnCloseRequest((w_evt) -> Platform.exit());

    Optional<ButtonType> response = alert.showAndWait();

    if (!response.isPresent() || response.get() != ButtonType.OK) {
        if (logger.isDebugEnabled()) {
            logger.debug("[RESET DATA FILE] reset cancelled");
        }

        exitCode = ExitCodeType.CANCELLED;
        passwordMatches.setValue(false);

        synchronized (this) {
            this.notify();
        }

    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("[RESET DATA FILE] reset");
        }

        configurationDataSource.deleteDataFile();

        exitCode = ExitCodeType.RESET;
        passwordMatches.setValue(false);

        synchronized (this) {
            this.notify();
        }
    }
}

From source file:com.mesosphere.dcos.cassandra.scheduler.resources.TasksResource.java

@GET
@Path("/{name}/info")
public DaemonInfo getInfo(@PathParam("name") final String name) {

    Optional<CassandraDaemonTask> taskOption = Optional.ofNullable(state.getDaemons().get(name));
    if (taskOption.isPresent()) {
        return DaemonInfo.create(taskOption.get());
    } else {//from  www  .ja v a 2 s .c om
        throw new NotFoundException();
    }
}

From source file:tds.assessment.services.impl.AccommodationServiceImpl.java

@Override
@Cacheable(CacheType.LONG_TERM)//from   w  ww  . j a v a 2s  . c  o m
public List<Accommodation> findAccommodationsByAssessmentKey(final String clientName,
        final String assessmentKey) {
    //Implements the replacement for CommonDLL.TestKeyAccommodations_FN
    Optional<Assessment> maybeAssessment = assessmentService.findAssessment(clientName, assessmentKey);
    if (!maybeAssessment.isPresent()) {
        throw new NotFoundException("Could not find assessment for %s", assessmentKey);
    }

    Assessment assessment = maybeAssessment.get();
    return accommodationsQueryRepository.findAssessmentAccommodationsByKey(assessment.getKey(),
            assessment.getLanguageCodes());
}

From source file:com.github.lukaszbudnik.dqueue.OrderedQueueClientIntegrationTest.java

@Test
public void shouldPublishSequential() throws ExecutionException, InterruptedException {
    Future<ImmutableList<UUID>> futures = queueClient.publishOrdered(
            new Item(UUIDs.timeBased(), ByteBuffer.wrap("A".getBytes())),
            new Item(UUIDs.timeBased(), ByteBuffer.wrap("B".getBytes())),
            new Item(UUIDs.timeBased(), ByteBuffer.wrap("C".getBytes())));
    futures.get();/* w  w w  .  j a va2  s .  co  m*/

    Future<Optional<OrderedItem>> optionalFutureA = queueClient.consumeOrdered();
    Optional<OrderedItem> itemOptionalA = optionalFutureA.get();
    OrderedItem itemA = itemOptionalA.get();

    assertNotNull(itemA);
    assertEquals("A", new String(itemA.getContents().array()));

    Future<Optional<OrderedItem>> optionalFutureB = queueClient.consumeOrdered();
    Optional<OrderedItem> itemOptionalB = optionalFutureB.get();

    assertFalse(itemOptionalB.isPresent());

    queueClient.deleteOrdered(itemA);

    optionalFutureB = queueClient.consumeOrdered();
    itemOptionalB = optionalFutureB.get();
    OrderedItem itemB = itemOptionalB.get();

    assertNotNull(itemB);
    assertEquals("B", new String(itemB.getContents().array()));

    Future<Optional<OrderedItem>> optionalFutureC = queueClient.consumeOrdered();
    Optional<OrderedItem> itemOptionalC = optionalFutureC.get();

    assertFalse(itemOptionalC.isPresent());

    queueClient.deleteOrdered(itemB);

    optionalFutureC = queueClient.consumeOrdered();
    itemOptionalC = optionalFutureC.get();
    OrderedItem itemC = itemOptionalC.get();

    assertNotNull(itemC);
    assertEquals("C", new String(itemC.getContents().array()));

    queueClient.deleteOrdered(itemC);

    Future<Optional<OrderedItem>> empty = queueClient.consumeOrdered();
    assertFalse(empty.get().isPresent());
}

From source file:com.netflix.genie.web.data.repositories.jpa.CriteriaResolutionRepositoryImpl.java

private String buildEntityQueryForType(final Criterion criterion, final CriteriaType criteriaType) {
    final Set<String> tags = criterion.getTags();
    final boolean hasTags = !tags.isEmpty();
    final StringBuilder query = new StringBuilder();
    query.append("SELECT c.id as id FROM ").append(criteriaType.getPrimaryTable()).append(" c");

    if (hasTags) {
        query.append(" join ").append(criteriaType.getTagTable()).append(" ct on c.id = ct.")
                .append(criteriaType.getTagJoinColumn()).append(" join tags t on ct.tag_id = t.id");
    }/*from ww  w  .j ava2s. c o m*/

    query.append(" WHERE");

    criterion.getId().ifPresent(id -> {
        if (StringUtils.isNotBlank(id)) {
            query.append(" c.unique_id = '").append(id).append("' AND");
        }
    });
    criterion.getName().ifPresent(name -> {
        if (StringUtils.isNotBlank(name)) {
            query.append(" c.name = '").append(name).append("' AND");
        }
    });
    criterion.getVersion().ifPresent(version -> {
        if (StringUtils.isNotBlank(version)) {
            query.append(" c.version = '").append(version).append("' AND");
        }
    });

    if (hasTags) {
        query.append(" t.tag IN (").append(criterion.getTags().stream().map(tag -> "'" + tag + "'")
                .reduce((first, second) -> first + ", " + second).orElse("")).append(") AND");
    }

    final String status;
    final Optional<String> criterionStatus = criterion.getStatus();
    if (criterionStatus.isPresent()) {
        final String unwrappedStatus = criterionStatus.get();
        status = StringUtils.isBlank(unwrappedStatus) ? criteriaType.getDefaultStatus() : unwrappedStatus;
    } else {
        status = criteriaType.getDefaultStatus();
    }
    query.append(" c.status = '").append(status).append("'");

    if (hasTags) {
        query.append(" GROUP BY c.id HAVING COUNT(c.id) = ").append(criterion.getTags().size());
    }

    return query.toString();
}

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

public List<BuildModel> getBuilds(String namespace, String name, int page, int size) {
    Optional<Project> projectOptional = projectDao.findByNamespaceNameAndName(namespace, name);
    Page<Build> builds = buildDao.findByProject(projectOptional.get(),
            new PageRequest(page, size, Sort.Direction.DESC, "creationDate"));
    return builds.getContent().stream().map(BuildMapper::mapBuild).collect(toList());
}