Example usage for java.util Optional ofNullable

List of usage examples for java.util Optional ofNullable

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public static <T> Optional<T> ofNullable(T value) 

Source Link

Document

Returns an Optional describing the given value, if non- null , otherwise returns an empty Optional .

Usage

From source file:com.kazuki43zoo.jpetstore.service.CatalogService.java

public Item getItem(String itemId) {
    return Optional.ofNullable(itemMapper.getItem(itemId))
            .orElseThrow(() -> new ResourceNotFoundException("Item", itemId));
}

From source file:com.sothawo.taboo2.Taboo2UserService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Optional<User> optionalUser;
    synchronized (knownUsers) {
        optionalUser = Optional.ofNullable(knownUsers.get(username));
        if (!optionalUser.isPresent()) {
            // reload the data from users file
            log.debug("loading user data");
            knownUsers.clear();// ww w. ja va 2s. co  m
            Optional.ofNullable(taboo2Configuration.getUsers()).ifPresent(filename -> {
                log.debug("user file: {}", filename);
                try {
                    Files.lines(Paths.get(filename)).map(String::trim).filter(line -> !line.isEmpty())
                            .filter(line -> !line.startsWith("#")).forEach(line -> {
                                String[] fields = line.split(":");
                                if (fields.length == 3) {
                                    String user = fields[0];
                                    String hashedPassword = fields[1];
                                    String[] roles = fields[2].split(",");
                                    if (roles.length < 1) {
                                        roles = new String[] { "undef" };
                                    }
                                    List<GrantedAuthority> authorities = new ArrayList<>();
                                    for (String role : roles) {
                                        authorities.add(new SimpleGrantedAuthority(role));
                                    }
                                    knownUsers.put(user, new User(user, hashedPassword, authorities));
                                }
                            });
                    log.debug("loaded {} user(s)", knownUsers.size());
                } catch (IOException e) {
                    log.debug("reading file", e);
                }
            });

            // search again after reload
            optionalUser = Optional.ofNullable(knownUsers.get(username));
        }
    }
    // need to return a copy as Spring security erases the password in the object after verification
    User user = optionalUser.orElseThrow(() -> new UsernameNotFoundException(username));
    return new User(user.getUsername(), user.getPassword(), user.getAuthorities());
}

From source file:io.gravitee.repository.redis.management.RedisEventRepository.java

@Override
public Optional<Event> findById(String eventId) throws TechnicalException {
    RedisEvent redisEvent = eventRedisRepository.find(eventId);
    return Optional.ofNullable(convert(redisEvent));
}

From source file:org.ow2.proactive.connector.iaas.cloud.TagManager.java

/**
 * Collect tags and ensure that mandatory connector-iaas tag key is not duplicated
 *
 * @param instanceOptions   instance's options that may contain tags
 * @return  the list of all tags//w w  w .ja  va 2 s  . c om
 */
public List<Tag> retrieveAllTags(Options instanceOptions) {
    List<Tag> tags = new ArrayList<>();
    tags.add(connectorIaasTag);
    Optional.ofNullable(instanceOptions).map(Options::getTags).ifPresent(optionalTags -> {
        tags.addAll(optionalTags.stream()
                .filter(optionalTag -> !optionalTag.getKey().equals(connectorIaasTag.getKey()))
                .collect(Collectors.toList()));
    });
    return tags;
}

From source file:org.apache.ambari.view.web.service.PackageServiceImpl.java

@Override
public Optional<PackageVersion> getVersion(Long versionId) {
    return Optional.ofNullable(packageVersionRepository.findOne(versionId));
}

From source file:com.javafxpert.wikibrowser.WikiLangLinksController.java

@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> locatorEndpoint(@RequestParam(value = "title") String articleTitle,
        @RequestParam(value = "lang") String lang) {

    String language = wikiBrowserProperties.computeLang(lang);

    LangLinksResponseNear langLinksResponseNear = null;
    if (!articleTitle.equals("")) {
        langLinksResponseNear = retrieveLangLinks(articleTitle, language);
    }/*from  ww  w .  j av a  2s .  co m*/

    return Optional.ofNullable(langLinksResponseNear)
            .map(cr -> new ResponseEntity<>((Object) cr, HttpStatus.OK))
            .orElse(new ResponseEntity<>("Wikipedia query unsuccessful", HttpStatus.INTERNAL_SERVER_ERROR));
}

From source file:com.kite9.k9server.LoggingInterceptor.java

private static Charset getCharset(HttpMessage message) {
    return Optional.ofNullable(message.getHeaders().getContentType()).map(MediaType::getCharset)
            .orElse(DEFAULT_CHARSET);// www . j  a  v  a 2  s . co  m
}

From source file:fi.helsinki.opintoni.security.authorization.portfolio.PortfolioRequestResolver.java

private Optional<PortfolioDto> getPortfolioDtoByPath(Map<String, String> templateVariables) {
    return Optional.ofNullable(portfolioService.findByPath(templateVariables.get("path"),
            PortfolioRole.fromValue(templateVariables.get("portfolioRole")),
            PortfolioConverter.ComponentFetchStrategy.NONE));
}

From source file:org.jodconverter.boot.autoconfigure.JodConverterOnlineAutoConfiguration.java

private OfficeManager createOfficeManager() {

    final OnlineOfficeManager.Builder builder = OnlineOfficeManager.builder();

    builder.urlConnection(properties.getUrl());
    builder.poolSize(properties.getPoolSize());
    builder.workingDir(properties.getWorkingDir());
    builder.taskExecutionTimeout(properties.getTaskExecutionTimeout());
    builder.taskQueueTimeout(properties.getTaskQueueTimeout());
    builder.sslConfig(Optional.ofNullable(properties.getSsl()).map(ssl -> {
        final SslConfig sslConfig = new SslConfig();
        sslConfig.setEnabled(ssl.isEnabled());
        sslConfig.setCiphers(ssl.getCiphers());
        sslConfig.setKeyAlias(ssl.getKeyAlias());
        sslConfig.setKeyPassword(ssl.getKeyPassword());
        sslConfig.setKeyStore(ssl.getKeyStore());
        sslConfig.setKeyStorePassword(ssl.getKeyStorePassword());
        sslConfig.setKeyStoreType(ssl.getKeyStoreType());
        sslConfig.setKeyStoreProvider(ssl.getKeyStoreProvider());
        sslConfig.setEnabledProtocols(ssl.getEnabledProtocols());
        sslConfig.setTrustStore(ssl.getTrustStore());
        sslConfig.setTrustStorePassword(ssl.getTrustStorePassword());
        sslConfig.setTrustStoreType(ssl.getTrustStoreType());
        sslConfig.setTrustStoreProvider(ssl.getTrustStoreProvider());
        sslConfig.setProtocol(ssl.getProtocol());
        sslConfig.setVerifyHostname(ssl.isVerifyHostname());
        return sslConfig;
    }).orElse(null));//  www . j  a  va  2  s.c om

    // Starts the manager
    return builder.build();
}

From source file:com.largecode.interview.rustem.service.UsersServiceImpl.java

@Override
public void updateUser(Long id, UserDto userDto, Role roleOfCreator) {
    LOGGER.debug("Update user id = {} with data {}", id, userDto);
    Optional<User> userInDb = Optional.ofNullable(userRepository.findOne(id));
    userInDb.ifPresent((user) -> {//from w ww.j  ava 2 s  . com
        roleOfCreator.modifyUserProperties(userDto, user);
        userRepository.saveAndFlush(user);
    });
    userInDb.orElseThrow(
            () -> new NoSuchElementException(String.format("User=%s not found for updating.", id)));

}