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:io.soabase.web.filters.LanguageFilter.java

@Override
public String getLanguageCode(HttpHeaders httpHeaders, UriInfo uriInfo) {
    javax.ws.rs.core.Cookie cookie = httpHeaders.getCookies().get(cookieName);
    Optional<String> cookieValue = Optional.ofNullable((cookie != null) ? cookie.getValue() : null);
    return getLanguageCode(uriInfo.getRequestUri().getQuery(), cookieValue);
}

From source file:alfio.controller.AdminConfigurationController.java

@RequestMapping(CONNECT_REDIRECT_PATH)
public String authorize(Principal principal, @RequestParam("state") String state,
        @RequestParam(value = "code", required = false) String code,
        @RequestParam(value = "error", required = false) String errorCode,
        @RequestParam(value = "error_description", required = false) String errorDescription,
        HttpSession session, RedirectAttributes redirectAttributes) {

    return Optional.ofNullable(session.getAttribute(STRIPE_CONNECT_ORG)).map(Integer.class::cast)
            .filter(orgId -> userManager
                    .isOwnerOfOrganization(userManager.findUserByUsername(principal.getName()), orgId))
            .map(orgId -> {//from   w w w .  j av a2  s .c  om
                session.removeAttribute(STRIPE_CONNECT_ORG);
                String persistedState = (String) session.getAttribute(STRIPE_CONNECT_STATE_PREFIX + orgId);
                session.removeAttribute(STRIPE_CONNECT_STATE_PREFIX + orgId);
                boolean stateVerified = Objects.equals(persistedState, state);
                if (stateVerified && code != null) {
                    StripeManager.ConnectResult connectResult = stripeManager.storeConnectedAccountId(code,
                            Configuration.from(orgId));
                    if (connectResult.isSuccess()) {
                        return "redirect:/admin/#/configuration/organization/" + orgId;
                    }
                } else if (stateVerified && StringUtils.isNotEmpty(errorCode)) {
                    log.warn("error from stripe. {}={}", errorCode, errorDescription);
                    redirectAttributes.addFlashAttribute("errorMessage",
                            StringUtils.defaultString(errorDescription, errorCode));
                    return "redirect:/admin/";
                }
                redirectAttributes.addFlashAttribute("errorMessage",
                        "Couldn't connect your account. Please retry.");
                return "redirect:/admin/";
            }).orElse("redirect:/admin/");
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchHadoopUtils.java

/** 
 * @param input_config - the input settings
 * @return//  w ww.j  av a2s.c o m
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static IAnalyticsAccessContext<InputFormat> getInputFormat(final Client client,
        final AnalyticThreadJobBean.AnalyticThreadJobInputBean job_input) {
    return new IAnalyticsAccessContext<InputFormat>() {
        private LinkedHashMap<String, Object> _mutable_output = null;

        @Override
        public String describe() {
            //(return the entire thing)
            return ErrorUtils.get("service_name={0} options={1}",
                    this.getAccessService().right().value().getSimpleName(), this.getAccessConfig().get());
        }

        /* (non-Javadoc)
         * @see com.ikanow.aleph2.data_model.interfaces.data_analytics.IAnalyticsAccessContext#getAccessService()
         */
        @Override
        public Either<InputFormat, Class<InputFormat>> getAccessService() {
            return Either.right((Class<InputFormat>) (Class<?>) Aleph2EsInputFormat.class);
        }

        /* (non-Javadoc)
         * @see com.ikanow.aleph2.data_model.interfaces.data_analytics.IAnalyticsAccessContext#getAccessConfig()
         */
        @Override
        public Optional<Map<String, Object>> getAccessConfig() {
            if (null != _mutable_output) {
                return Optional.of(_mutable_output);
            }
            _mutable_output = new LinkedHashMap<>();

            // Check for input record limit:
            Optional.ofNullable(job_input.config()).map(cfg -> cfg.test_record_limit_request()).ifPresent(
                    max -> _mutable_output.put(Aleph2EsInputFormat.BE_DEBUG_MAX_SIZE, Long.toString(max)));

            final String index_resource = ElasticsearchContext.READ_PREFIX
                    + ElasticsearchIndexUtils.getBaseIndexName(BeanTemplateUtils.build(DataBucketBean.class)
                            .with(DataBucketBean::full_name, job_input.resource_name_or_id()).done().get(),
                            Optional.empty())
                    + "*";

            //TODO (ALEPH-72): support multi-buckets / buckets with non-standard indexes ... also use the tmin/tmax
            // (needs MDB to pull out - because need to get the full bucket ugh)

            // Currently need to add types: 
            //TODO (ALEPH-72): 2.2.0 you _can_ just put "indexes/" to get all types - that doesn't work for all es-hadoop code though
            final Multimap<String, String> index_type_mapping = ElasticsearchIndexUtils.getTypesForIndex(client,
                    index_resource);
            final String type_resource = index_type_mapping.values().stream().collect(Collectors.toSet())
                    .stream().collect(Collectors.joining(","));
            final String final_index = getTimedIndexes(job_input, index_type_mapping,
                    new Date())
                            .map(s -> Stream
                                    .concat(s,
                                            TimeSliceDirUtils.getUntimedDirectories(
                                                    index_type_mapping.keySet().stream()))
                                    .collect(Collectors.joining(",")))
                            .orElse(index_resource);

            _mutable_output.put("es.resource", final_index + "/" + type_resource);

            _mutable_output.put("es.read.metadata", "true");
            _mutable_output.put("es.read.metadata.field", Aleph2EsInputFormat.ALEPH2_META_FIELD);

            _mutable_output.put("es.index.read.missing.as.empty", "yes");

            _mutable_output.put("es.query",
                    Optional.ofNullable(job_input.filter()).map(f -> f.get("technology_override")).map(o -> {
                        return (o instanceof String) ? o.toString()
                                : _mapper.convertValue(o, JsonNode.class).toString();
                    }).orElse("?q=*"));
            //TODO (ALEPH-72) (incorporate tmin/tmax and also add a JSON mapping for the Aleph2 crud utils)

            // Here are the parameters that can be set:
            // es.query ... can be stringified JSON or a q=string .... eg conf.set("es.query", "?q=me*");  
            //config.set("es.resource", overallIndexNames.toString()); .. .this was in the format X,Y,Z[/type],,etc which then got copied to 
            // create a simple multi-input format .. looks like i didn't do anything if no type was set, unclear if that was an optimization
            // or if it doesn't work... (if it doesn't work then what you have to do is get the mappings for each index and
            // get the types and insert them all)
            //config.set("es.index.read.missing.as.empty", "yes");

            // (not sure if need to set just normal http port/host?)
            //config.set("es.net.proxy.http.host", "localhost");
            //config.set("es.net.proxy.http.port", "8888");

            return Optional.of(Collections.unmodifiableMap(_mutable_output));
        }
    };
}

From source file:eu.agilejava.snoopee.client.SnoopEEProducer.java

private String readProperty(final String key, Map<String, Object> snoopConfig) {

    String property = Optional.ofNullable(System.getProperty(key)).orElseGet(() -> {
        String envProp = Optional.ofNullable(System.getenv(key)).orElseGet(() -> {
            String confProp = Optional.ofNullable(snoopConfig.get(key)).orElseThrow(() -> {
                return new SnoopEEConfigurationException(
                        key + " must be configured either in snoopee.yml or as env or system property");
            }).toString();//from w  ww  .j  a v a 2s. c  om
            return confProp;
        });
        return envProp;
    });

    return property;
}

From source file:fi.hsl.parkandride.back.LockDao.java

protected Optional<Lock> selectLockIfExists(String lockName) {
    return Optional
            .ofNullable(queryFactory.from(qLock).where(qLock.name.eq(lockName)).select(lockMapping).fetchOne());
}

From source file:se.crisp.codekvast.agent.daemon.worker.impl.ScpFileUploaderImpl.java

private String getUploadToUsername(DaemonConfig config) {
    return Optional.ofNullable(config.getUploadToUsername()).orElse(System.getProperty("user.name"));
}

From source file:com.microsoft.azure.hdinsight.sdk.rest.ObjectConvertUtils.java

public static <T> Optional<List<T>> convertXmlToList(@NotNull String jsonString, Class<T> tClass)
        throws IOException {
    List<T> myLists = xmlMapper.readValue(jsonString,
            TypeFactory.defaultInstance().constructCollectionType(List.class, tClass));
    return Optional.ofNullable(myLists);
}

From source file:com.devicehive.service.DeviceEquipmentServiceTest.java

@Test
public void should_update_device_equipment() throws Exception {
    DeviceUpdate du = new DeviceUpdate();
    du.setGuid(Optional.ofNullable(RandomStringUtils.randomAlphabetic(10)));
    du.setName(Optional.ofNullable(RandomStringUtils.randomAlphabetic(10)));
    DeviceClassUpdate dc = new DeviceClassUpdate();
    dc.setName(Optional.ofNullable(RandomStringUtils.randomAlphabetic(10)));
    du.setDeviceClass(Optional.ofNullable(dc));
    deviceService.deviceSave(du, Collections.<DeviceClassEquipmentVO>emptySet());

    DeviceVO device = deviceService.findByGuidWithPermissionsCheck(du.getGuid().orElse(null), null);

    DeviceEquipmentVO devo = new DeviceEquipmentVO();
    devo.setCode(RandomStringUtils.randomAlphabetic(10));
    deviceEquipmentService.createDeviceEquipment(devo, device);

    DeviceEquipmentVO saved = deviceEquipmentService.findByCodeAndDevice(devo.getCode(), device);

    saved.setParameters(new JsonStringWrapper("{\"param\": \"value\"}"));
    deviceEquipmentService.createDeviceEquipment(saved, device);

    DeviceEquipmentVO updated = deviceEquipmentService.findByCodeAndDevice(devo.getCode(), device);
    assertThat(saved.getId(), equalTo(updated.getId()));
    assertThat(updated.getParameters().getJsonString(), equalTo("{\"param\": \"value\"}"));
}

From source file:org.workspace7.moviestore.controller.HomeController.java

@GetMapping("/")
public ModelAndView home(ModelAndView modelAndView, HttpServletRequest request) {

    final String hostname = System.getenv().getOrDefault("HOSTNAME", "unknown");
    log.info("Request served by HOST {} ", hostname);

    HttpSession session = request.getSession(false);

    List<Movie> movies = movieDBHelper.getAll();

    List<MovieCartItem> movieList = movies.stream()
            .map((Movie movie) -> MovieCartItem.builder().movie(movie).quantity(1).total(0).build())
            .collect(Collectors.toList());

    if (session != null) {
        AdvancedCache<String, Object> sessionCache = (AdvancedCache<String, Object>) cacheManager
                .getCache("moviestore-sessions-cache").getNativeCache();

        Optional<MapSession> mapSession = Optional.ofNullable((MapSession) sessionCache.get(session.getId()));

        log.info("Session already exists, retrieving values from session {}", mapSession);

        int cartCount = 0;

        if (mapSession.isPresent()) {

            MovieCart movieCart = mapSession.get().getAttribute(ShoppingCartController.SESSION_ATTR_MOVIE_CART);

            if (movieCart != null) {

                log.info("Movie Cart:{} for session id:{}", movieCart, session.getId());

                final Map<String, Integer> movieItems = movieCart.getMovieItems();

                movieList = movieList.stream().map(movieCartItem -> {
                    Movie movie = movieCartItem.getMovie();
                    String movieId = movie.getId();
                    if (movieItems.containsKey(movieId)) {
                        int quantity = movieItems.get(movieId);
                        movieCartItem.setQuantity(quantity);
                    } else {
                        movieCartItem.setQuantity(1);
                    }//  www .  j a v  a2  s.  c om
                    return movieCartItem;

                }).collect(Collectors.toList());

                cartCount = movieItems.size();
            }
        }
        modelAndView.addObject("cartCount", cartCount);
        modelAndView.addObject("movies", movieList);
    } else {
        log.info("New Session");
        modelAndView.addObject("movies", movieList);
    }
    modelAndView.setViewName("home");
    modelAndView.addObject("hostname", hostname);
    return modelAndView;
}

From source file:net.kemitix.checkstyle.ruleset.builder.DefaultReadmeIndexBuilder.java

private String level(final Rule rule) {
    return Optional.ofNullable(rule.getLevel()).orElse(RuleLevel.UNSPECIFIED).toString().toLowerCase(LOCALE);
}