List of usage examples for java.util Optional of
public static <T> Optional<T> of(T value)
From source file:enmasse.controller.api.v3.amqp.AmqpFlavorsApiTest.java
@Test public void testGet() throws IOException { Message response = doRequest("GET", "", Optional.of("flavor1")); ObjectNode data = decodeJson(response); assertThat(data.get("kind").asText(), is("Flavor")); assertThat(data.get("metadata").get("name").asText(), is("flavor1")); assertThat(data.get("spec").get("type").asText(), is("queue")); assertThat(data.get("spec").get("description").asText(), is("Simple queue")); }
From source file:com.bekwam.resignator.model.ConfigurationDataSourceImpl.java
@Override public void init() throws Exception { if (logger.isDebugEnabled()) { logger.debug("[INIT]"); }/* ww w .j a va2 s.c om*/ configuration = Optional.of(new Configuration()); initFileSystem(); }
From source file:com.blackducksoftware.integration.hub.detect.util.TildeInPathResolver.java
public Optional<String> resolveTildeInValue(final String value) { final String originalString = value; if (StringUtils.isNotBlank(originalString)) { final String resolvedPath = resolveTildeInPath(currentOs, systemUserHome, originalString); if (!resolvedPath.equals(originalString)) { logger.warn(String.format( "We have resolved %s to %s. If this is not expected, please revise the path provided, or specify --detect.resolve.tilde.in.paths=false.", originalString, resolvedPath)); return Optional.of(resolvedPath); }//ww w . j a v a 2s . co m } return Optional.empty(); }
From source file:net.hamnaberg.json.generator.CollectionGeneratorTest.java
@Test public void itemsCollection() throws Exception { List<Item> items = new ArrayList<Item>(); items.add(Item.create(COLLECTION_URI.resolve("item/1"), Arrays.asList(Property.value("one", Optional.of("One"), ValueFactory.createOptionalValue(1))), Collections.<Link>emptyList())); JsonNode collection = Collection.builder(COLLECTION_URI).addItems(items).build().asJson(); assertNotNull(collection);/*from w w w. j a v a 2s. com*/ assertEquals("1.0", collection.get("version").asText()); assertEquals(COLLECTION_URI.toString(), collection.get("href").asText()); assertEquals(createItems(), collection.get("items")); }
From source file:com.spotify.ffwd.signalfx.SignalFxOutputPlugin.java
@JsonCreator public SignalFxOutputPlugin(@JsonProperty("sourceName") String sourceName, @JsonProperty("authToken") String authToken, @JsonProperty("flushInterval") Optional<Long> flushInterval, @JsonProperty("batching") Optional<Batching> batching, @JsonProperty("soTimeout") Integer soTimeout, @JsonProperty("filter") Optional<Filter> filter) { super(filter, Batching.from(flushInterval, batching, Optional.of(DEFAULT_FLUSH_INTERVAL))); this.sourceName = Optional.ofNullable(sourceName).orElse(DEFAULT_SOURCE_NAME); this.authToken = Optional.ofNullable(authToken) .orElseThrow(() -> new IllegalArgumentException("authToken: must be defined")); this.soTimeout = Optional.ofNullable(soTimeout).orElse(DEFAULT_SO_TIMEOUT); }
From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchHadoopUtils.java
/** * @param input_config - the input settings * @return/*from w w w . j a v a2s . com*/ */ @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:com.willwinder.universalgcodesender.utils.FirmwareUtils.java
/** * Gets a list of command processors initialized with user settings. *//* w w w . ja v a 2 s. com*/ public static Optional<List<CommandProcessor>> getParserFor(String firmware, Settings settings) throws Exception { if (!configFiles.containsKey(firmware)) { throw new Exception("Missing config file."); } return Optional.of(configFiles.get(firmware).loader.getProcessors()); }
From source file:alfio.manager.user.UserManager.java
public List<UserWithOrganizations> findAllUsers(String username) { List<Organization> organizations = findUserOrganizations(username); Predicate<Collection<?>> isNotEmpty = ks -> !ks.isEmpty(); return Optional.of(organizations).filter(isNotEmpty).flatMap(org -> { Map<Integer, List<UserOrganization>> usersAndOrganizations = userOrganizationRepository .findByOrganizationIdsOrderByUserId( organizations.stream().map(Organization::getId).collect(toList())) .stream().collect(Collectors.groupingBy(UserOrganization::getUserId)); return Optional.of(usersAndOrganizations.keySet()).filter(isNotEmpty) .map(ks -> userRepository.findByIds(ks).stream().map(u -> { List<UserOrganization> userOrganizations = usersAndOrganizations.get(u.getId()); return new UserWithOrganizations(u, organizations.stream().filter( o -> userOrganizations.stream().anyMatch(uo -> uo.getOrganizationId() == o.getId())) .collect(toList())); }).collect(toList()));// www . j a v a 2s . c o m }).orElseGet(Collections::emptyList); }
From source file:com.michellemay.matchers.MatchersFactory.java
private Matcher createMacher(MatcherConfig matcherConfig) { if (StringUtils.isBlank(matcherConfig.name)) { throw new IllegalArgumentException("Blank matcher name!"); }//from w ww.j a va 2s .c om if (matcherConfig.urlpart == null) { throw new IllegalArgumentException("Matcher must apply to an urlpart!"); } Optional<Mapping> mapping = Optional.empty(); if (matcherConfig.mapping != null) { if (StringUtils.isBlank(matcherConfig.mapping) || !mappingsFactory.getMappings().containsKey(matcherConfig.mapping)) { throw new IllegalStateException("Mapping '" + matcherConfig.mapping + "' does not exists!"); } mapping = Optional.of(mappingsFactory.getMappings().get(matcherConfig.mapping)); } if (matcherConfig.patterns == null || matcherConfig.patterns.isEmpty()) { throw new IllegalArgumentException("Matcher must have non-empty patterns list!"); } int flags = matcherConfig.casesensitive ? 0 : Pattern.CASE_INSENSITIVE; ArrayList<Pattern> patterns = Lists.newArrayList(); matcherConfig.patterns.forEach((patternStr) -> { // Must contain a capturing group named 'lang'. ex: (?<lang>\w+) if (!patternStr.contains("(?<lang>")) { throw new IllegalArgumentException( "Matcher pattern '" + patternStr + "' must have a capturing group named 'lang'!"); } patterns.add(Pattern.compile(patternStr, flags)); }); return createMatcher(matcherConfig.name, matcherConfig.urlpart).withPatterns(patterns) .withCaseSensitive(matcherConfig.casesensitive).withMapping(mapping) .withPatternOrder(matcherConfig.patternorder); }
From source file:example.springdata.jpa.simple.SimpleUserRepositoryTests.java
@Test public void useOptionalAsReturnAndParameterType() { assertThat(repository.findByUsername(Optional.of("foobar")), is(Optional.empty())); repository.save(user);//w w w . ja v a 2 s . c om assertThat(repository.findByUsername(Optional.of("foobar")).isPresent(), is(true)); }