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:org.openmhealth.shim.jawbone.mapper.JawboneBodyEventsDataPointMapper.java

/**
 * Handles some of the basic measure creation activities for body event datapoints and then delegates the creation
 * of the {@link Builder} to subclasses for each individual body event {@link Measure}.
 *
 * @param listEntryNode an individual entry node from the "items" array of a Jawbone endpoint response
 *//*from w  w w  . j a v a 2s.co  m*/
@Override
protected Optional<T> getMeasure(JsonNode listEntryNode) {

    if (!containsType(listEntryNode, getBodyEventType())) {
        return Optional.empty();
    }

    Optional<Measure.Builder<T, ?>> builderOptional = newMeasureBuilder(listEntryNode);
    if (!builderOptional.isPresent()) {
        return Optional.empty();
    }

    Measure.Builder<T, ?> builder = builderOptional.get();

    setEffectiveTimeFrame(builder, listEntryNode);

    Optional<String> optionalUserNote = asOptionalString(listEntryNode, "note");
    optionalUserNote.ifPresent(builder::setUserNotes);

    return Optional.of(builder.build());
}

From source file:com.netflix.genie.web.tasks.node.DiskCleanupTask.java

/**
 * Checks the disk for jobs on this host. Deletes any job directories that are older than the desired
 * retention and are complete./*w w w. j  a  v a  2s .  c o m*/
 */
@Override
public void run() {
    log.info("Running disk cleanup task...");
    final File[] jobDirs = this.jobsDir.listFiles();
    if (jobDirs == null) {
        log.warn("No job dirs found. Returning.");
        this.numberOfDeletedJobDirs.set(0);
        this.numberOfDirsUnableToDelete.set(0);
        return;
    }
    // For each of the directories figure out if we need to delete the files or not
    long deletedCount = 0;
    long unableToDeleteCount = 0;
    for (final File dir : jobDirs) {
        if (!dir.isDirectory()) {
            log.info("File {} isn't a directory. Skipping.", dir.getName());
            continue;
        }

        final String id = dir.getName();
        try {
            final Job job = this.jobSearchService.getJob(id);
            if (job.getStatus().isActive()) {
                // Don't want to delete anything still going
                continue;
            }

            // Delete anything with a finish time before today @12 AM UTC - retention
            final Calendar retentionThreshold = TaskUtils.getMidnightUTC();
            TaskUtils.subtractDaysFromDate(retentionThreshold, this.properties.getRetention());
            final Optional<Date> finished = job.getFinished();
            if (finished.isPresent() && finished.get().before(retentionThreshold.getTime())) {
                log.info("Attempting to delete job directory for job {}", id);
                if (this.runAsUser) {
                    final CommandLine commandLine = new CommandLine("sudo");
                    commandLine.addArgument("rm");
                    commandLine.addArgument("-rf");
                    commandLine.addArgument(dir.getAbsolutePath());
                    this.processExecutor.execute(commandLine);
                } else {
                    // Save forking a process ourselves if we don't have to
                    FileUtils.deleteDirectory(dir);
                }
                deletedCount++;
                log.info("Successfully deleted job directory for job {}", id);
            }
        } catch (final GenieException ge) {
            log.error("Unable to get job {}. Continuing.", id, ge);
            this.unableToGetJobCounter.increment();
            unableToDeleteCount++;
        } catch (final IOException ioe) {
            log.error("Unable to delete job directory for job with id: {}", id, ioe);
            this.unableToDeleteJobDirCounter.increment();
            unableToDeleteCount++;
        }
    }
    this.numberOfDeletedJobDirs.set(deletedCount);
    this.numberOfDirsUnableToDelete.set(unableToDeleteCount);
}

From source file:com.galenframework.storage.controllers.api.PageApiController.java

private PageObject findOrCreatePageObject(Page page, String elementName) {
    Optional<PageObject> pageObject = objectRepository.findObject(page.getPageId(), elementName);
    if (pageObject.isPresent()) {
        return pageObject.get();
    } else {//from ww w  .ja va 2 s  .c  o  m
        PageObject po = new PageObject();
        po.setPageId(page.getPageId());
        po.setName(elementName);
        Long elementId = objectRepository.createObject(po);
        po.setObjectId(elementId);
        return po;
    }
}

From source file:io.gravitee.gateway.reactor.handler.impl.DefaultReactorHandlerResolver.java

@Override
public ReactorHandler resolve(Request request) {
    StringBuilder path = new StringBuilder(request.path());

    if (path.charAt(path.length() - 1) != '/') {
        path.append('/');
    }/*from  w w w.ja va 2 s . com*/

    Optional<ReactorHandler> handlers = handlerRegistry.getReactorHandlers().stream()
            .filter(handler -> path.toString().startsWith(handler.contextPath())).findFirst();

    if (handlers.isPresent()) {
        ReactorHandler handler = handlers.get();
        LOGGER.debug("Returning the first handler matching path {} : {}", path, handler);
        return handler;
    }

    return null;
}

From source file:com.uber.hoodie.common.model.HoodieFileGroup.java

/**
 * Obtain the latest log file (based on latest committed data file),
 * currently being appended to/*from   w  ww .  j  a va2 s. co  m*/
 *
 * @return logfile if present, empty if no log file has been opened already.
 */
public Optional<HoodieLogFile> getLatestLogFile() {
    Optional<FileSlice> latestSlice = getLatestFileSlice();
    if (latestSlice.isPresent() && latestSlice.get().getLogFiles().count() > 0) {
        return latestSlice.get().getLogFiles().findFirst();
    }
    return Optional.empty();
}

From source file:com.todo.backend.security.UserDetailsServiceImpl.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    log.trace(".loadUserByUsername({})", username);

    final String lowercaseUsername = username.toLowerCase();
    final Optional<User> optionalUser = userRepository.findByUsername(lowercaseUsername);

    if (!optionalUser.isPresent()) {
        throw new UsernameNotFoundException("User " + username + " not found!");
    }/*from   w  w  w .j  av  a  2s.com*/

    final User user = optionalUser.get();
    final List<GrantedAuthority> grantedAuthorities = Collections
            .singletonList(new SimpleGrantedAuthority(user.getRole().name()));
    return new org.springframework.security.core.userdetails.User(lowercaseUsername, null, grantedAuthorities);
}

From source file:io.kamax.mxisd.lookup.provider.DnsLookupProvider.java

@Override
public Optional<SingleLookupReply> find(SingleLookupRequest request) {
    if (!ThreePidMedium.Email.is(request.getType())) { // TODO use enum
        log.info("Skipping unsupported type {} for {}", request.getType(), request.getThreePid());
        return Optional.empty();
    }//from  www. j ava  2 s .  c om

    log.info("Performing DNS lookup for {}", request.getThreePid());

    String domain = request.getThreePid().substring(request.getThreePid().lastIndexOf("@") + 1);
    log.info("Domain name for {}: {}", request.getThreePid(), domain);
    Optional<String> baseUrl = findIdentityServerForDomain(domain);

    if (baseUrl.isPresent()) {
        return fetcher.find(baseUrl.get(), request);
    }

    return Optional.empty();
}

From source file:com.lithium.flow.shell.tunnel.ShellTunneler.java

@Nonnull
public Tunnel getTunnel(@Nonnull String host, int port, @Nullable String through) throws IOException {
    List<Login> logins = Lists.newArrayList();

    Login endLogin = access.getLogin(host);
    logins.add(endLogin);//  w  w w. j a v a  2  s  .  c o  m

    if (through != null) {
        logins.add(access.getLogin(through));
    }

    Optional<String> match = config.getMatch("shell.tunnels", endLogin.getHost());
    if (match.isPresent()) {
        for (String tunnel : Splitter.on(';').split(match.get())) {
            logins.add(access.getLogin(tunnel));
        }
    }

    Collections.reverse(logins);

    Tunnel tunnel = null;
    for (int i = 0; i < logins.size() - 1; i++) {
        Login thisLogin = logins.get(i);
        Login nextLogin = logins.get(i + 1);
        if (i == logins.size() - 2) {
            nextLogin = nextLogin.toBuilder().setPort(port).build();
        }

        log.debug("tunneling through {} to {}", thisLogin, nextLogin.getHostAndPort());

        Login login = thisLogin;
        if (tunnel != null) {
            login = login.toBuilder().setHost("localhost").setPort(tunnel.getPort()).build();
        }

        String message = login.getKeyPath() != null ? login.getKeyPath() : thisLogin.getDisplayString();
        Function<Boolean, String> pass = retry -> access.getPrompt().prompt(message, message, true, retry);
        login = login.toBuilder().setPass(pass).build();

        tunnel = shore.getShell(login).tunnel(0, nextLogin.getHost(), nextLogin.getPortOrDefault(22));
    }

    if (tunnel != null) {
        tunnels.add(tunnel);
        return tunnel;
    } else {
        return new NoTunnel(host, port);
    }
}

From source file:com.ejisto.util.collector.MockedFieldCollector.java

@Override
public Function<Map<String, List<MockedField>>, FieldNode> finisher() {
    return map -> {
        FieldNode root = new FieldNode(null, null);
        map.entrySet().stream().filter(e -> !e.getValue().isEmpty()).flatMap(EXTRACT_ENTRY).forEach(entry -> {
            MockedField first = entry.getValue().get(0);
            Optional<FieldNode> parent = root.findDirectParent(first);
            if (!parent.isPresent()) {
                parent = root.findClosestParent(first);
            }// www. ja  v  a2 s.  c o m
            final FieldNode parentNode = parent.get();
            FieldNode container = parentNode.fillGap(first);
            entry.getValue().forEach(v -> container.addChild(new FieldNode(v)));
        });
        return root;
    };
}

From source file:dpfmanager.shell.modules.messages.MessagesModule.java

private void tractAlertMessage(AlertMessage am) {
    Platform.runLater(new Runnable() {
        @Override/*from   www.  j ava  2  s.com*/
        public void run() {
            Alert alert;
            // Create alert
            if (am.getType().equals(AlertMessage.Type.CONFIRMATION)) {
                alert = AlertsManager.createConfirmationAlert(am);
            } else {
                alert = AlertsManager.createSimpleAlert(am);
            }

            // Show alert
            if (!am.getType().equals(AlertMessage.Type.CONFIRMATION)) {
                alert.showAndWait();
                if (am.getNext() != null) {
                    context.send(am.getTarget(), am.getNext());
                }
            } else {
                Optional<ButtonType> result = alert.showAndWait();
                am.setResult(result.get().getButtonData().equals(ButtonBar.ButtonData.YES));
                context.send(am.getSourceId(), am);
            }
        }
    });
}