Example usage for java.util Optional isPresent

List of usage examples for java.util Optional isPresent

Introduction

In this page you can find the example usage for java.util Optional isPresent.

Prototype

public boolean isPresent() 

Source Link

Document

If a value is present, returns true , otherwise false .

Usage

From source file:com.github.blindpirate.gogradle.task.go.test.PlainGoTestResultExtractor.java

private List<Pair<Integer, String>> extractStartIndiceAndTestMethodNames(List<String> stdout) {
    List<Pair<Integer, String>> ret = new ArrayList<>();

    for (int i = 0; i < stdout.size(); ++i) {
        Optional<String> testName = getRootTestNameFromLine(stdout.get(i));
        if (testName.isPresent()) {
            ret.add(Pair.of(i, testName.get()));
        }//from   w  w  w. j  a va2 s.c  o  m
    }
    return ret;
}

From source file:io.fabric8.vertx.maven.plugin.mojos.InitializeMojo.java

private void copyJSDependencies(Set<Artifact> dependencies) throws MojoExecutionException {
    for (Artifact artifact : dependencies) {
        if (artifact.getType().equalsIgnoreCase("js")) {
            Optional<File> file = getArtifactFile(artifact);
            if (file.isPresent()) {
                try {
                    if (stripJavaScriptDependencyVersion) {
                        String name = artifact.getArtifactId();
                        if (artifact.getClassifier() != null) {
                            name += "-" + artifact.getClassifier();
                        }/*  w ww.  j av  a2  s .c  om*/
                        name += ".js";
                        File output = new File(createWebRootDirIfNeeded(), name);
                        FileUtils.copyFile(file.get(), output);
                    } else {
                        FileUtils.copyFileToDirectory(file.get(), createWebRootDirIfNeeded());
                    }
                } catch (IOException e) {
                    throw new MojoExecutionException("Unable to copy '" + artifact.toString() + "'", e);
                }
            } else {
                getLog().warn(
                        "Skipped the copy of '" + artifact.toString() + "' - The artifact file does not exist");
            }
        }
    }
}

From source file:com.minitwit.web.AuthenticationController.java

/**
 * Process the Registration page.// w w  w. j  a v  a 2s  .  co m
 * 
 * @param user
 *   The {@link User} object bound to the registration form fields.
 * @param request
 *   The HTTP POST request.
 * 
 * @return
 *   The View (with Model) to render in response.
 */
@RequestMapping(value = "/register", method = POST)
public ModelAndView registrationSubmit(@ModelAttribute("user") final User user, final WebRequest request) {
    Optional<String> error = user.validate();
    if (!error.isPresent()) {
        Optional<User> userExists = twitSvc.getUserbyUsername(user.getUsername());
        if (!userExists.isPresent()) {
            twitSvc.registerUser(user);
            return new ModelAndView(new RedirectView("/"));
        }
        error = Optional.of("The username is already taken.");
    }
    final ModelAndView nav = new ModelAndView("register");
    nav.addObject("user", user);
    nav.addObject("error", error.get());
    return nav;
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.view.provider.KubernetesV2ManifestProvider.java

@Override
public KubernetesV2Manifest getManifest(String account, String location, String name) {
    Pair<KubernetesKind, String> parsedName;
    try {//  w  w w.jav a 2  s  . com
        parsedName = KubernetesManifest.fromFullResourceName(name);
    } catch (Exception e) {
        return null;
    }

    KubernetesKind kind = parsedName.getLeft();
    String key = Keys.infrastructure(kind, account, location, parsedName.getRight());

    Optional<CacheData> dataOptional = cacheUtils.getSingleEntry(kind.toString(), key);
    if (!dataOptional.isPresent()) {
        return null;
    }

    CacheData data = dataOptional.get();
    KubernetesResourceProperties properties = registry.get(account, kind);
    if (properties == null) {
        return null;
    }

    Function<KubernetesManifest, String> lastEventTimestamp = (
            m) -> (String) m.getOrDefault("lastTimestamp", m.getOrDefault("firstTimestamp", "n/a"));

    List<KubernetesManifest> events = cacheUtils
            .getTransitiveRelationship(kind.toString(), Collections.singletonList(key),
                    KubernetesKind.EVENT.toString())
            .stream().map(KubernetesCacheDataConverter::getManifest)
            .sorted(Comparator.comparing(lastEventTimestamp)).collect(Collectors.toList());

    KubernetesHandler handler = properties.getHandler();

    KubernetesManifest manifest = KubernetesCacheDataConverter.getManifest(data);
    Moniker moniker = KubernetesCacheDataConverter.getMoniker(data);

    return new KubernetesV2Manifest().builder().account(account).location(location).manifest(manifest)
            .moniker(moniker).status(handler.status(manifest)).artifacts(handler.listArtifacts(manifest))
            .events(events).build();
}

From source file:net.pkhsolutions.pecsapp.boundary.PictureServiceBean.java

@Override
public @NotNull Optional<InputStream> downloadPictureForLayout(@NotNull PictureDescriptor descriptor,
        @NotNull PageLayout layout) {/*  w  w w  .  ja  va2  s. c om*/
    LOGGER.debug("Downloading picture for descriptor {} and layout {}", descriptor, layout);
    try {
        Optional<BufferedImage> image = scalingPictureFileStorage.loadForLayout(descriptor, layout);
        if (image.isPresent()) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image.get(), descriptor.getMimeType().getSubtype(), baos);
            return Optional.of(new ByteArrayInputStream(baos.toByteArray()));
        } else {
            return Optional.empty();
        }
    } catch (IOException ex) {
        LOGGER.error("Error downloading picture", ex);
        throw new DownloadPictureException("Could not download picture", ex);
    }
}

From source file:com.adobe.ags.curly.controller.ActionGroupRunner.java

private Optional<Exception> withClient(Function<CloseableHttpClient, Optional<Exception>> process) {
    if (client == null) {
        client = clientSupplier.apply(false);
    }/*from   w  ww . j a  va  2s  .  co  m*/
    Optional<Exception> ex = process.apply(client);
    if (ex.isPresent() && ex.get() instanceof IllegalStateException) {
        System.err.println("Error in HTTP request - RETRYING: " + ex.get().getMessage());
        ex.get().printStackTrace();
        client = clientSupplier.apply(true);
        ex = process.apply(client);
    }
    if (ex.isPresent()) {
        System.err.println("Error in HTTP request, abandoning client: " + ex.get().getMessage());
        ex.get().printStackTrace();
        client = null;
    }
    return ex;
}

From source file:ch.fihlon.moodini.business.token.control.TokenService.java

public Optional<String> authorize(@NotNull final String email, @NotNull final String challengeValue) {
    Optional<String> token = Optional.empty();

    final Optional<User> user = userService.readByEmail(email);
    if (user.isPresent()) {
        final Challenge cachedChallenge = challengeCache.getIfPresent(email);
        if (cachedChallenge != null) {
            if (challengeValue.equals(cachedChallenge.getChallenge())
                    && cachedChallenge.getTries() < MAXIMAL_WRONG_CHALENGE_TRIES) {
                token = Optional.of(generateToken(user.get()));
                challengeCache.invalidate(email);
            } else {
                cachedChallenge.increaseTries();
            }//from w  ww . j av a 2 s .c om
        }
    }

    return token;
}

From source file:org.ameba.aop.ServiceLayerAspect.java

/**
 * Called after an exception is thrown by classes of the service layer. <p> Set log level to ERROR to log the root cause. </p>
 *
 * @param ex The root exception that is thrown
 * @return Returns the exception to be thrown
 *///from  w w w .  j a  v  a 2  s.  c o  m
public Exception translateException(Exception ex) {
    if (ex instanceof BusinessRuntimeException) {
        BusinessRuntimeException bre = (BusinessRuntimeException) ex;
        MDC.put(LoggingCategories.MSGKEY, bre.getMsgKey());
        if (bre.getData() != null) {
            MDC.put(LoggingCategories.MSGDATA,
                    String.join(",", Stream.of(bre.getData()).map(Object::toString).toArray(String[]::new)));
        }
        // cleanup of context is done in SLF4JMappedDiagnosticContextFilter
        return bre;
    }

    Optional<Exception> handledException = doTranslateException(ex);
    if (handledException.isPresent()) {
        return handledException.get();
    }
    if (ex instanceof ServiceLayerException) {
        return ex;
    }
    return withRootCause ? new ServiceLayerException(ex.getMessage(), ex)
            : new ServiceLayerException(ex.getMessage());
}

From source file:be.neutrinet.ispng.VPN.java

@Override
public void init(DaemonContext dc) throws Exception {
    Logger root = Logger.getRootLogger();
    root.setLevel(Level.INFO);/*from   ww w.  j a v a  2 s . com*/
    root.addAppender(new ConsoleAppender(LAYOUT));

    cfg = new Properties();
    cfg.load(new FileInputStream("config.properties"));

    root.addAppender(
            new DailyRollingFileAppender(LAYOUT, cfg.getProperty("log.file", "ispng.log"), "'.'yyyy-MM-dd"));

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            Logger.getLogger(getClass()).error("Unhandled exception", e);
        }
    });

    Zookeeper.boot(cfg.getProperty("zookeeper.connectionString"));
    Config.get().boot();
    generator = new Generator();

    Config.get().getAndWatch("log/level", "INFO", level -> root.setLevel(Level.toLevel(level)));

    Optional<String> dbUser = Config.get("db/user");
    if (!dbUser.isPresent()) {
        cs = new JdbcConnectionSource(Config.get("db/uri").get());
    } else {
        if (cfg.get("db.uri").toString().contains("mariadb")) {
            cs = new JdbcConnectionSource(cfg.getProperty("db.uri"), cfg.getProperty("db.user"),
                    cfg.getProperty("db.password"), new MariaDBType());
        } else if (cfg.get("db.uri").toString().contains("mysql")) {
            cs = new JdbcConnectionSource(cfg.getProperty("db.uri"), cfg.getProperty("db.user"),
                    cfg.getProperty("db.password"), new MySQLDBType());
        } else {
            cs = new JdbcConnectionSource(cfg.getProperty("db.uri"), cfg.getProperty("db.user"),
                    cfg.getProperty("db.password"));
        }
    }
}

From source file:com.linksinnovation.elearning.controller.api.QuizController.java

@RequestMapping(value = "/score/{courseId}", method = RequestMethod.GET)
public QuizScore getScore(@PathVariable("courseId") Long courseId, @AuthenticationPrincipal String username) {
    UserDetails userDetails = userDetailsRepository.findOne(username);
    Course course = courseRepositroy.findOne(courseId);
    Optional<QuizScore> quizscore = quizScoreRepository.findByUserAndCourse(userDetails, course);
    if (quizscore.isPresent()) {
        return quizscore.get();
    } else {/*from w  w w.  j  a va  2s  .  c om*/
        return null;
    }
}