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:org.apache.ambari.view.web.controller.PackageController.java

@GetMapping("/{id}")
public PackageWrapper.FindOneResponse getOne(@PathVariable("id") Long packageId) {
    Optional<Package> packageOptional = service.getPackage(packageId);
    if (!packageOptional.isPresent()) {
        log.error("Package id: {} not found", packageId);
        throw new RuntimeException("Package not found");
    }/*from   ww  w  .  j a v  a2  s . c  o m*/
    return new PackageWrapper.FindOneResponse(packageOptional.get());
}

From source file:cloudfoundry.norouter.f5.dropsonde.LoggingPoolPopulator.java

private boolean containsSelf(Optional<Collection<PoolMember>> poolMembers, InetSocketAddress poolMember) {
    return poolMembers.isPresent() && poolMembers.get().stream()
            .filter(member -> member.getName().equalsIgnoreCase(poolMember.toString())).findFirst().isPresent();
}

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 a v a 2s  .c o  m

    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.dfox.junit.http.example.NoteServlet.java

@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    addBasicHeaders(response);//from w  w w .  j  a va 2 s.co m

    String name = getNoteName(request);

    Optional<InputStream> note = repository.getNote(name);
    if (note.isPresent()) {
        try (InputStream noteStream = note.get()) {
            try (OutputStream outputStream = response.getOutputStream()) {
                IOUtils.copy(noteStream, outputStream);
            }
        }
    } else {
        response.setStatus(404);
    }
}

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 w  w .j a  v a  2s. com*/

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

From source file:it.polimi.diceH2020.launcher.service.Validator.java

public boolean validateClassParameters(Path pathToFile) {
    Optional<ClassParametersMap> sol = objectFromPath(pathToFile, ClassParametersMap.class);
    return (sol.isPresent() && sol.get().validate());
}

From source file:com.openthinks.webscheduler.controller.ProfileController.java

@Mapping("/base/edit")
public String editBaseInfo(WebAttributers was) {
    String email = was.get(StaticDict.PAGE_PARAM_USER_EMAIL);
    try {/*from ww  w . ja  v a  2  s .  c o  m*/
        Checker.require(email).notEmpty("User email can not be empty.");
    } catch (Exception e) {
        was.addError(StaticDict.PAGE_ATTRIBUTE_ERROR_1, e.getMessage(), WebScope.REQUEST);
        return StaticUtils.errorPage(was, PageMap.build());
    }
    Optional<User> currentUser = getCurrentUser(was);

    if (!currentUser.isPresent()) {
        was.addError(StaticDict.PAGE_ATTRIBUTE_ERROR_1, "Session timeout, please login again.",
                WebScope.REQUEST);
        return StaticUtils.errorPage(was, PageMap.build());
    }
    User user = currentUser.get();
    if (!email.equals(user.getEmail())) {
        User duplicateUser = securityService.getUsers().findByEmail(email);
        if (duplicateUser != null) {
            was.addError(StaticDict.PAGE_ATTRIBUTE_ERROR_1,
                    "Couldn't update profile, maybe this email has already been used.", WebScope.REQUEST);
            return StaticUtils.errorPage(was, PageMap.build());
        }
    }
    user.setEmail(email);
    securityService.saveToDisk();
    return WebUtils.redirect("/profile/index");
}

From source file:org.onebusaway.alexa.MainSpeechlet.java

public SpeechletResponse onLaunch(LaunchRequest request, Session session) throws SpeechletException {
    Optional<ObaUserDataItem> optUserData = obaDao.getUserData(session);
    if (optUserData.isPresent()) {
        try {//from  w  w w .j  a v  a  2 s.  c om
            return getAuthedSpeechlet(optUserData.get()).onLaunch(request, session);
        } catch (URISyntaxException e) {
            log.error("Launch exception: " + e.getMessage());
            log.error("Backtrace:\n" + e.getStackTrace());
            throw new SpeechletException("Error creating user data on Launch using ObaBaseUrl: " + e);
        }
    } else {
        return anonSpeechlet.onLaunch(request, session);
    }
}

From source file:com.galenframework.ide.controllers.DomSnapshotController.java

public void initRoutes() {
    post("/api/dom-snapshots", (req, res) -> {
        String url = req.params().get("url");
        String source = req.params().get("source");
        if (url == null || source == null) {
            DomSnapshotRequest snapshotRequest = mapper.readValue(req.body(), DomSnapshotRequest.class);
            url = snapshotRequest.getUrl();
            source = snapshotRequest.getSource();
        }/*  w w w.j  a va2s  .  c om*/
        return domSnapshotService.createSnapshot(source, url);
    });

    get("/api/dom-snapshots/:domId/snapshot.html", (req, res) -> {
        res.header("Content-Type", "text/html");
        String domId = req.params("domId");
        if (domId != null && !domId.trim().isEmpty()) {
            Optional<DomSnapshot> domSnapshot = domSnapshotService.getDomSnapshot(domId);
            if (domSnapshot.isPresent()) {
                return domSnapshot.get().getOriginSource();
            } else {
                return "Can't find DOM snapshot for key: " + domId;
            }
        } else
            throw new RuntimeException("Incorrect request, missing domId");
    });
}

From source file:it.polimi.diceH2020.launcher.service.Validator.java

public boolean validateVMConfigurations(Path pathToFile) {
    Optional<VMConfigurationsMap> sol = objectFromPath(pathToFile, VMConfigurationsMap.class);
    return (sol.isPresent() && sol.get().validate());
}