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.largecode.interview.rustem.controller.UsersController.java

private void checkEmailNotExists(UserDto userDto, String operationName) {
    Optional<User> user = usersService.getUserByEmail(userDto.getEmail());
    if (user.isPresent()) {
        if (!user.get().getIdUser().equals(userDto.getIdUser())) {
            throw new ExceptionOtherUserWithSameEmail(
                    String.format("Can not %s because other User (%s) already exists with the same email '%s'.",
                            operationName, user.get().getIdUser(), userDto.getEmail()));
        }// w  ww .j a v  a  2 s.c  om
    }
}

From source file:com.arpnetworking.configuration.jackson.JsonNodePaginatedUriSource.java

private JsonNodePaginatedUriSource(final Builder builder) {
    super(builder);
    _uri = builder._uri;//  w  w w .j  a va  2  s.c  om
    _dataKeys = builder._dataKeys.toArray(new String[builder._dataKeys.size()]);
    _nextPageKeys = builder._nextPageKeys.toArray(new String[builder._nextPageKeys.size()]);

    final JsonNodeMergingSource.Builder mergingSourceBuilder = new JsonNodeMergingSource.Builder();
    try {
        final URIBuilder uriBuilder = new URIBuilder(_uri);
        URI currentUri = uriBuilder.build();
        while (currentUri != null) {
            LOGGER.debug().setMessage("Creating JsonNodeUriSource for page").addData("uri", currentUri).log();

            // Create a URI source for the page
            final JsonNodeUriSource uriSource = new JsonNodeUriSource.Builder().setUri(currentUri).build();
            mergingSourceBuilder.addSource(uriSource);

            // Extract the link for the next page
            final Optional<JsonNode> nextPageNode = uriSource.getValue(_nextPageKeys);
            if (nextPageNode.isPresent() && !nextPageNode.get().isNull()) {
                final String nextPagePath = nextPageNode.get().asText();

                final URI nextPageUri = URI
                        .create(nextPagePath.startsWith("/") ? nextPagePath : "/" + nextPagePath);
                final URIBuilder nextPageUriBuilder = new URIBuilder(nextPageUri);
                currentUri = uriBuilder.setPath(nextPageUri.getPath())
                        .setParameters(nextPageUriBuilder.getQueryParams()).build();
            } else {
                currentUri = null;
            }
        }
    } catch (final URISyntaxException e) {
        throw Throwables.propagate(e);
    }

    _mergingSource = mergingSourceBuilder.build();
}

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

@Test
public void shouldPublishAndConsumePreservingStartTimeOrder() throws ExecutionException, InterruptedException {
    Integer routingKey = 3;/*from   www . ja va2 s  .  c o m*/
    Integer version = 123;
    Integer type = 1;

    UUID startTime1 = UUIDs.timeBased();
    UUID startTime2 = UUIDs.timeBased();
    UUID startTime3 = UUIDs.timeBased();
    ByteBuffer contents1 = ByteBuffer.wrap("contents1".getBytes());
    ByteBuffer contents2 = ByteBuffer.wrap("contents2".getBytes());
    ByteBuffer contents3 = ByteBuffer.wrap("contents3".getBytes());

    ImmutableMap.Builder<String, Object> filters = ImmutableMap.builder();
    filters.put("type", type).put("version", version).put("routing_key", routingKey);

    Future<UUID> publishFuture1 = queueClient.publish(new Item(startTime1, contents1, filters.build()));
    publishFuture1.get();

    Future<UUID> publishFuture2 = queueClient.publish(new Item(startTime2, contents2, filters.build()));
    publishFuture2.get();

    Future<UUID> publishFuture3 = queueClient.publish(new Item(startTime3, contents3, filters.build()));
    publishFuture3.get();

    Future<Optional<Item>> itemFuture1 = queueClient.consume(filters.build());
    Optional<Item> item1 = itemFuture1.get();
    UUID consumedStartTime1 = item1.get().getStartTime();
    assertEquals(startTime1, consumedStartTime1);

    Future<Optional<Item>> itemFuture2 = queueClient.consume(filters.build());
    Optional<Item> item2 = itemFuture2.get();
    UUID consumedStartTime2 = item2.get().getStartTime();
    assertEquals(startTime2, consumedStartTime2);

    Future<Optional<Item>> itemFuture3 = queueClient.consume(filters.build());
    Optional<Item> item3 = itemFuture3.get();
    UUID consumedStartTime3 = item3.get().getStartTime();
    assertEquals(startTime3, consumedStartTime3);
}

From source file:com.epam.ta.reportportal.core.widget.impl.GetWidgetHandler.java

private boolean isFilterUnShared(String userName, String project, Optional<UserFilter> userFilter) {
    return userFilter.isPresent()
            && !AclUtils.isPossibleToReadResource(userFilter.get().getAcl(), userName, project);
}

From source file:org.obiba.mica.dataset.DatasetCacheResolver.java

@Override
public Collection<? extends Cache> resolveCaches(
        CacheOperationInvocationContext<?> cacheOperationInvocationContext) {
    Collection<Cache> res = Lists.newArrayList();

    Optional<Object> dataset = Arrays.stream(cacheOperationInvocationContext.getArgs())
            .filter(o -> o instanceof Dataset).findFirst();

    if (dataset.isPresent()) {
        String cacheName = "dataset-" + ((Dataset) dataset.get()).getId();
        Cache datasetCache = springCacheManager.getCache(cacheName);

        if (datasetCache == null) {
            CacheConfiguration conf = cacheManager.getEhcache("dataset-variables").getCacheConfiguration()
                    .clone();/*from  w w w .  ja  v  a  2 s  . c  om*/
            conf.setName(cacheName);
            cacheManager.addCache(new net.sf.ehcache.Cache(conf));
            net.sf.ehcache.Cache cache = cacheManager.getCache(cacheName);
            cacheManager.replaceCacheWithDecoratedCache(cache,
                    InstrumentedEhcache.instrument(metricRegistry, cache));
            datasetCache = new EhCacheCache(cacheManager.getEhcache(cacheName));
        }

        res.add(datasetCache);
    }

    return res;
}

From source file:com.formkiq.core.form.bean.FormJSONDateFieldInterceptor.java

@Override
public void setValue(final FormJSON form) {

    SimpleDateFormat df = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
    Optional<FormJSONField> inserted = FormFinder.findValueByKey(form, "insertedDate");
    Optional<FormJSONField> updated = FormFinder.findValueByKey(form, "updatedDate");

    String date = df.format(new Date());
    if (inserted.isPresent() && isEmpty(inserted.get().getValue())) {
        inserted.get().setValue(date);// w w  w.j  av a  2s  . c  o m
    }

    if (updated.isPresent()) {
        updated.get().setValue(date);
    }
}

From source file:com.astamuse.asta4d.web.form.flow.base.StepAwaredValidationFormHelper.java

static final Object getValidationTargetByAnnotation(Object form, String step) {
    String cacheKey = step + "@" + form.getClass().getName();
    Optional<Field> oField = ValidationTargetFieldCache.get(cacheKey);

    if (oField == null) {
        List<Field> list = new ArrayList<>(ClassUtil.retrieveAllFieldsIncludeAllSuperClasses(form.getClass()));
        Iterator<Field> it = list.iterator();
        while (it.hasNext()) {
            Field f = it.next();//from  w  w w  . j a  v a 2 s .  c o  m
            StepAwaredValidationTarget vtAnno = f.getAnnotation(StepAwaredValidationTarget.class);
            if (vtAnno == null) {
                continue;
            }
            String representingStep = vtAnno.value();
            if (step.equals(representingStep)) {
                oField = Optional.of(f);
                break;
            }
        }
        if (oField == null) {
            oField = Optional.empty();
        }
        if (Configuration.getConfiguration().isCacheEnable()) {
            Map<String, Optional<Field>> newCache = new HashMap<>(ValidationTargetFieldCache);
            newCache.put(cacheKey, oField);
            ValidationTargetFieldCache = newCache;
        }
    }

    if (oField.isPresent()) {
        try {
            return FieldUtils.readField(oField.get(), form, true);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    } else {
        return form;
    }
}

From source file:com.blackducksoftware.integration.hub.detect.detector.gradle.GradleInspectorManager.java

public String getGradleInspector() throws DetectorException {
    if (!hasResolvedInspector) {
        hasResolvedInspector = true;/*from w ww  .j  av  a2s  .  c  om*/
        try {
            final File airGapPath = deriveGradleAirGapDir();
            final File generatedGradleScriptFile = directoryManager.getSharedFile(GRADLE_DIR_NAME,
                    GENERATED_GRADLE_SCRIPT_NAME);
            GradleScriptCreator gradleScriptCreator = new GradleScriptCreator(detectConfiguration,
                    configuration);
            if (airGapPath == null) {
                Optional<String> version = findVersion();
                if (version.isPresent()) {
                    logger.info("Resolved the gradle inspector version: " + version.get());
                    generatedGradleScriptPath = gradleScriptCreator
                            .generateOnlineScript(generatedGradleScriptFile, version.get());
                } else {
                    throw new DetectorException(
                            "Unable to find the gradle inspector version from artifactory.");
                }
            } else {
                generatedGradleScriptPath = gradleScriptCreator.generateAirGapScript(generatedGradleScriptFile,
                        airGapPath.getCanonicalPath());
            }
        } catch (final Exception e) {
            throw new DetectorException(e);
        }
        if (generatedGradleScriptPath == null) {
            throw new DetectorException("Unable to initialize the gradle inspector.");
        } else {
            logger.trace("Derived generated gradle script path: " + generatedGradleScriptPath);
        }
    } else {
        logger.debug("Already attempted to resolve the gradle inspector script, will not attempt again.");
    }
    if (StringUtils.isBlank(generatedGradleScriptPath)) {
        throw new DetectorException("Unable to find or create the gradle inspector script.");
    }
    return generatedGradleScriptPath;
}

From source file:com.github.achatain.catalog.servlet.CollectionIdServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    LOG.info("Look up the collection " + extractCollectionIdFromRequest(req));

    final String userId = getUserId(req);
    final String colId = extractCollectionIdFromRequest(req);

    final Optional<CollectionDto> optionalCollectionDto = collectionService.readCollection(userId, colId);

    if (optionalCollectionDto.isPresent()) {
        final CollectionDto col = optionalCollectionDto.get();
        final String href = removeEnd(req.getRequestURL().toString(), "/");
        final String hrefItems = format("%s/items", href);
        col.addLink(Link.create().withRel("self").withMethod(Link.Method.GET).withHref(href).build());
        col.addLink(Link.create().withRel("edit").withMethod(Link.Method.PUT).withHref(href).build());
        col.addLink(Link.create().withRel("delete").withMethod(Link.Method.DELETE).withHref(href).build());
        col.addLink(Link.create().withRel("list").withMethod(Link.Method.GET).withHref(hrefItems).build());
        col.addLink(Link.create().withRel("add").withMethod(Link.Method.POST).withHref(hrefItems).build());

        final String hrefIndexes = format("%s/indexes", href);
        col.getFields()//from w  w  w.j a v a  2 s .c o  m
                .forEach(fieldDto -> fieldDto
                        .addLink(Link.create().withRel(fieldDto.isIndexed() ? "dropIndex" : "createIndex")
                                .withMethod(fieldDto.isIndexed() ? Link.Method.DELETE : Link.Method.POST)
                                .withHref(format("%s/%s", hrefIndexes, fieldDto.getName())).build()));

        sendResponse(resp, col);
    } else {
        sendNotFoundError(resp, format("No collection was found with id [%s]", colId));
    }
}

From source file:gallerydemo.menu.ManagementMenuController.java

public ManagementMenuController(GalleryDemoViewController controller) {

    super(controller, "ManagementMenu.fxml");

    this.actualizeButtons();

    this.newGalleryButton.setOnAction((ActionEvent event) -> {
        this.createGalleryOrFolder(true);
    });/*w  w  w  .  ja  va2s.c  o  m*/

    this.newFolderButton.setOnAction((ActionEvent event) -> {
        this.createGalleryOrFolder(false);
    });

    this.galleryPropertiesButton.setOnAction((ActionEvent event) -> {
        GalleryNode g = this.controller.getActiveGallery();

        if (g.isTrunk()) {
            return;
        }

        TextInputDialog dialog = new TextInputDialog(g.getName());
        dialog.setTitle("Umbenennen");
        dialog.setHeaderText(
                g.isGallery() ? "Die ausgewhlte Galerie umbenennen" : "Den ausgewhlten Ordner umbenennen");
        dialog.setContentText("Neuer Name:");

        Optional<String> result = dialog.showAndWait();
        if (result.isPresent()) {
            g.setName(result.get());
            g.saveConfigFile();
        }
    });

    this.deleteGalleryButton.setOnAction((ActionEvent event) -> {
        GalleryNode g = this.controller.getActiveGallery();

        if (g.isTrunk()) {
            return;
        }

        Alert alert = new Alert(AlertType.CONFIRMATION);
        alert.setTitle("Lschen");
        alert.setHeaderText(
                g.isGallery() ? "Die ausgewhlte Galerie lschen?" : "Den ausgewhlten Ordner lschen?");
        alert.setContentText("Unwiederruflicher Vorgang!");

        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == ButtonType.OK) {
            GalleryNode parent = (GalleryNode) g.getParent();
            Logger.getLogger("logfile").log(Level.INFO, "[delete] {0}", g.getLocation());
            try {
                FileUtils.deleteDirectory(g.getLocation());
            } catch (IOException ex) {
                Logger.getLogger("logfile").log(Level.SEVERE, null, ex);
            } finally {
                // Remove deleted gallery from tree view
                parent.getChildren().remove(g);
                this.controller.setActiveGallery(parent);
            }
        }
    });
}