List of usage examples for com.google.common.collect ImmutableMap isEmpty
@Override public boolean isEmpty()
From source file:com.isotrol.impe3.pms.core.obj.PortalObject.java
List<SetFilterDTO> getSetFilterDTOs() { ImmutableMap<String, SetFilterValue> filters = setFilters.get(); final List<SetFilterDTO> list = Lists.newArrayListWithCapacity(filters.size()); if (filters.isEmpty()) { return list; }//from www . j ava 2 s. co m for (String set : Ordering.natural().sortedCopy(filters.keySet())) { SetFilterValue v = filters.get(set); SetFilterDTO dto = new SetFilterDTO(); dto.setName(set); dto.setType(v.getType()); dto.setDescription(v.getDescription()); list.add(dto); } return list; }
From source file:org.glowroot.transaction.AdviceCache.java
@EnsuresNonNull({ "reweavableAdvisors", "reweavableConfigVersions", "allAdvisors" }) public void updateAdvisors(/*>>>@UnknownInitialization(AdviceCache.class) AdviceCache this,*/ List<InstrumentationConfig> reweavableConfigs, boolean cleanTmpDir) throws Exception { ImmutableMap<Advice, LazyDefinedClass> advisors = AdviceGenerator.createAdvisors(reweavableConfigs, null); if (instrumentation == null) { // this is for tests that don't run with javaagent container ClassLoader loader = Thread.currentThread().getContextClassLoader(); checkNotNull(loader, "Context class loader must be set"); ClassLoaders.defineClassesInClassLoader(advisors.values(), loader); } else {/*from w w w . ja va 2 s.c om*/ File generatedJarDir = new File(dataDir, "tmp"); if (cleanTmpDir) { ClassLoaders.createDirectoryOrCleanPreviousContentsWithPrefix(generatedJarDir, "config-pointcuts"); } if (!advisors.isEmpty()) { String suffix = ""; int count = jarFileCounter.incrementAndGet(); if (count > 1) { suffix = "-" + count; } File jarFile = new File(generatedJarDir, "config-pointcuts" + suffix + ".jar"); ClassLoaders.defineClassesInBootstrapClassLoader(advisors.values(), instrumentation, jarFile); } } reweavableAdvisors = advisors.keySet().asList(); reweavableConfigVersions = createReweavableConfigVersions(reweavableConfigs); allAdvisors = ImmutableList.copyOf(Iterables.concat(pluginAdvisors, reweavableAdvisors)); }
From source file:org.elasticsearch.search.query.sortbydoc.SortByDocQueryParser.java
@Override public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); String currentFieldName = null; String lookupIndex = parseContext.index().name(); String lookupType = null;/*ww w.j a v a2 s. com*/ String lookupId = null; String rootPath = null; String idField = null; String scoreField = null; String lookupRouting = null; SortOrder sortOrder = SortOrder.DESC; Query subQuery = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { if ("query".equals(parser.currentName())) { subQuery = parseContext.parseInnerQuery(); continue; } } else if (token.isValue()) { if (false) { } else if ("index".equals(currentFieldName)) { lookupIndex = parser.text(); } else if ("type".equals(currentFieldName)) { lookupType = parser.text(); } else if ("doc_id".equals(currentFieldName)) { lookupId = parser.text(); } else if ("root".equals(currentFieldName)) { rootPath = parser.text(); } else if ("id".equals(currentFieldName)) { idField = parser.text(); } else if ("score".equals(currentFieldName)) { scoreField = parser.text(); } else if ("routing".equals(currentFieldName)) { lookupRouting = parser.textOrNull(); } else if ("sort_order".equals(currentFieldName)) { try { sortOrder = SortOrder.valueOf(parser.text()); } catch (IllegalArgumentException e) { throw new QueryParsingException(parseContext, "[sort_by_doc] sort_order should be one of " + Arrays.toString(SortOrder.values())); } } else { throw new QueryParsingException(parseContext, "[sort_by_doc] query does not support [" + currentFieldName + "] within lookup element"); } } } if (lookupType == null) { throw new QueryParsingException(parseContext, "[sort_by_doc] query lookup element requires specifying the type"); } if (lookupId == null) { throw new QueryParsingException(parseContext, "[sort_by_doc] query lookup element requires specifying the doc_id"); } if (rootPath == null) { throw new QueryParsingException(parseContext, "[sort_by_doc] query lookup element requires specifying the path"); } if (idField == null) { throw new QueryParsingException(parseContext, "[sort_by_doc] query lookup element requires specifying the id"); } if (scoreField == null) { throw new QueryParsingException(parseContext, "[sort_by_doc] query lookup element requires specifying the score"); } if (subQuery == null) { throw new QueryParsingException(parseContext, "[sort_by_doc] query requires a subquery"); } String fieldName = "_id"; MappedFieldType _idType = parseContext.mapperService().smartNameFieldType(fieldName); /* FieldMapper fieldMapper = null; smartNameFieldMappers = parseContext.mapperService().smartFieldMappers(fieldName); if (smartNameFieldMappers != null) { if (smartNameFieldMappers.hasMapper()) { fieldMapper = smartNameFieldMappers.mapper(); fieldName = fieldMapper.names().indexName(); } } */ /* if (fieldMapper == null || !(fieldMapper instanceof IdFieldMapper)) throw new QueryParsingException(parseContext.index(), "[sort_by_doc] the _id field must be a defaultly indexed UID field"); */ if (_idType == null) throw new QueryParsingException(parseContext, "[sort_by_doc] the _id field must be a defaultly indexed UID field"); // external lookup, use it ScoresLookup scoresLookup = new ScoresLookup(lookupIndex, lookupType, lookupId, lookupRouting, rootPath, idField, scoreField, parseContext, SearchContext.current()); ImmutableMap<String, Float> scores = scoringDocumentCache.getScores(scoresLookup); Map<Term, Float> termsScores = new HashMap<>(); for (Map.Entry<String, Float> score : scores.entrySet()) { Uid.createUidsForTypesAndId(parseContext.queryTypes(), score.getKey()); BytesRef[] keyUids = Uid.createUidsForTypesAndId(parseContext.queryTypes(), score.getKey()); for (BytesRef keyUid : keyUids) { Term t = new Term(UidFieldMapper.NAME, keyUid); termsScores.put(t, sortOrder.equals(SortOrder.DESC) ? score.getValue() : -score.getValue()); } } if (scores.isEmpty()) { return subQuery; } Query filter = _idType.termsQuery(scores.keySet().asList(), parseContext); return new SortByDocQuery(fieldName, subQuery, filter, termsScores); }
From source file:org.glowroot.agent.impl.AdviceCache.java
@EnsuresNonNull({ "reweavableAdvisors", "reweavableConfigVersions", "allAdvisors" }) public void updateAdvisors(/*>>>@UnknownInitialization(AdviceCache.class) AdviceCache this,*/ List<InstrumentationConfig> reweavableConfigs, boolean cleanTmpDir) throws Exception { ImmutableMap<Advice, LazyDefinedClass> advisors = AdviceGenerator.createAdvisors(reweavableConfigs, null, true);/*from w w w . j av a 2s . c om*/ if (instrumentation == null) { // this is for tests that don't run with javaagent container ClassLoader loader = AdviceCache.class.getClassLoader(); checkNotNull(loader); ClassLoaders.defineClassesInClassLoader(advisors.values(), loader); } else { File generatedJarDir = new File(baseDir, "tmp"); if (cleanTmpDir) { ClassLoaders.createDirectoryOrCleanPreviousContentsWithPrefix(generatedJarDir, "config-pointcuts"); } if (!advisors.isEmpty()) { String suffix = ""; int count = jarFileCounter.incrementAndGet(); if (count > 1) { suffix = "-" + count; } File jarFile = new File(generatedJarDir, "config-pointcuts" + suffix + ".jar"); ClassLoaders.defineClassesInBootstrapClassLoader(advisors.values(), instrumentation, jarFile); } } reweavableAdvisors = advisors.keySet().asList(); reweavableConfigVersions = createReweavableConfigVersions(reweavableConfigs); allAdvisors = ImmutableList.copyOf(Iterables.concat(pluginAdvisors, reweavableAdvisors)); }
From source file:org.zanata.client.commands.push.RawPushCommand.java
/** * Validate file extensions//from w w w . j a v a 2s . c o m * @param inputFileType * @param userExtensions * @param acceptedTypes */ private void validateFileExtensions(@Nullable FileTypeName inputFileType, ImmutableMap<String, String> userExtensions, List<FileTypeInfo> acceptedTypes) { if (inputFileType != null) { return; } // if file type is missing but extensions are present, try to provide // a helpful error message if (userExtensions.isEmpty()) { //throw error if inputFileType and inputExtensions is empty throw new InvalidUserInputException("Invalid expression for '--file-types' option"); } else { //suggest --file-types options for this extension for (FileTypeInfo docType : acceptedTypes) { for (String srcExt : docType.getSourceExtensions()) { if (userExtensions.containsKey(srcExt)) { String msg = Messages.format("file.type.suggestFromExtension", docType, srcExt, docType); throw new InvalidUserInputException(msg); } } } throw new InvalidUserInputException("Invalid expression for '--file-types' option"); } }
From source file:com.google.javascript.jscomp.newtypes.NominalType.java
NominalType instantiateGenerics(Map<String, JSType> newTypeMap) { if (newTypeMap.isEmpty()) { return this; }// w ww.j av a 2 s. co m if (!this.rawType.isGeneric()) { return this.rawType.getAsNominalType(); } ImmutableMap.Builder<String, JSType> builder = ImmutableMap.builder(); ImmutableMap<String, JSType> resultMap; if (!typeMap.isEmpty()) { for (String oldKey : typeMap.keySet()) { builder.put(oldKey, typeMap.get(oldKey).substituteGenerics(newTypeMap)); } resultMap = builder.build(); } else { ImmutableList<String> typeParams = this.rawType.getTypeParameters(); for (String newKey : typeParams) { if (newTypeMap.containsKey(newKey)) { builder.put(newKey, newTypeMap.get(newKey)); } } resultMap = builder.build(); if (resultMap.isEmpty()) { return this; } // This works around a bug in FunctionType, because we can't know where // FunctionType#receiverType is coming from. // If the condition is true, receiverType comes from a method declaration, // and we should not create a new type here. if (resultMap.size() < typeParams.size()) { return this; } } return new NominalType(resultMap, this.rawType); }
From source file:org.lanternpowered.server.block.state.LanternBlockState.java
LanternBlockState(LanternBlockStateMap baseState, ImmutableMap<BlockTrait<?>, Comparable<?>> traitValues) { this.traitValues = traitValues; this.baseState = baseState; ImmutableBiMap.Builder<Key<Value<?>>, BlockTrait<?>> builder = ImmutableBiMap.builder(); for (BlockTrait trait : traitValues.keySet()) { builder.put(((LanternBlockTrait) trait).getKey(), trait); }/*www.j a v a 2 s . c o m*/ this.keyToBlockTrait = builder.build(); final StringBuilder idBuilder = new StringBuilder(); idBuilder.append( baseState.getBlockType().getId().substring(baseState.getBlockType().getPluginId().length() + 1)); if (!traitValues.isEmpty()) { idBuilder.append('['); final Joiner joiner = Joiner.on(','); final List<String> propertyValues = new ArrayList<>(); for (Map.Entry<BlockTrait<?>, Comparable<?>> entry : traitValues.entrySet()) { propertyValues.add( entry.getKey().getName() + "=" + entry.getValue().toString().toLowerCase(Locale.ENGLISH)); } idBuilder.append(joiner.join(propertyValues)); idBuilder.append(']'); } this.name = idBuilder.toString(); this.id = baseState.getBlockType().getPluginId() + ':' + this.name; }
From source file:google.registry.rdap.RdapJsonFormatter.java
/** * Creates a JSON object for a {@link HostResource}. * * @param hostResource the host resource object from which the JSON object should be created * @param isTopLevel if true, the top-level boilerplate will be added * @param linkBase the URL base to be used when creating links * @param whoisServer the fully-qualified domain name of the WHOIS server to be listed in the * port43 field; if null, port43 is not added to the object * @param now the as-date/*ww w. ja v a 2s .co m*/ * @param outputDataType whether to generate full or summary data */ ImmutableMap<String, Object> makeRdapJsonForHost(HostResource hostResource, boolean isTopLevel, @Nullable String linkBase, @Nullable String whoisServer, DateTime now, OutputDataType outputDataType) { ImmutableMap.Builder<String, Object> jsonBuilder = new ImmutableMap.Builder<>(); jsonBuilder.put("objectClassName", "nameserver"); jsonBuilder.put("handle", hostResource.getRepoId()); jsonBuilder.put("ldhName", hostResource.getFullyQualifiedHostName()); // Only include the unicodeName field if there are unicode characters. if (hasUnicodeComponents(hostResource.getFullyQualifiedHostName())) { jsonBuilder.put("unicodeName", Idn.toUnicode(hostResource.getFullyQualifiedHostName())); } jsonBuilder.put("status", makeStatusValueList(hostResource.getStatusValues())); jsonBuilder.put("links", ImmutableList.of(makeLink("nameserver", hostResource.getFullyQualifiedHostName(), linkBase))); List<ImmutableMap<String, Object>> remarks; // If we are outputting all data (not just summary data), also add events taken from the history // entries. If we are outputting summary data, instead add a remark indicating that fact. if (outputDataType == OutputDataType.SUMMARY) { remarks = ImmutableList.of(RdapIcannStandardInformation.SUMMARY_DATA_REMARK); } else { remarks = ImmutableList.of(); ImmutableList<Object> events = makeEvents(hostResource, now); if (!events.isEmpty()) { jsonBuilder.put("events", events); } } ImmutableSet<InetAddress> inetAddresses = hostResource.getInetAddresses(); if (!inetAddresses.isEmpty()) { ImmutableList.Builder<String> v4AddressesBuilder = new ImmutableList.Builder<>(); ImmutableList.Builder<String> v6AddressesBuilder = new ImmutableList.Builder<>(); for (InetAddress inetAddress : inetAddresses) { if (inetAddress instanceof Inet4Address) { v4AddressesBuilder.add(InetAddresses.toAddrString(inetAddress)); } else if (inetAddress instanceof Inet6Address) { v6AddressesBuilder.add(InetAddresses.toAddrString(inetAddress)); } } ImmutableMap.Builder<String, ImmutableList<String>> ipAddressesBuilder = new ImmutableMap.Builder<>(); ImmutableList<String> v4Addresses = v4AddressesBuilder.build(); if (!v4Addresses.isEmpty()) { ipAddressesBuilder.put("v4", Ordering.natural().immutableSortedCopy(v4Addresses)); } ImmutableList<String> v6Addresses = v6AddressesBuilder.build(); if (!v6Addresses.isEmpty()) { ipAddressesBuilder.put("v6", Ordering.natural().immutableSortedCopy(v6Addresses)); } ImmutableMap<String, ImmutableList<String>> ipAddresses = ipAddressesBuilder.build(); if (!ipAddresses.isEmpty()) { jsonBuilder.put("ipAddresses", ipAddressesBuilder.build()); } } if (whoisServer != null) { jsonBuilder.put("port43", whoisServer); } if (isTopLevel) { addTopLevelEntries(jsonBuilder, BoilerplateType.NAMESERVER, remarks, ImmutableList.<ImmutableMap<String, Object>>of(), linkBase); } else if (!remarks.isEmpty()) { jsonBuilder.put(REMARKS, remarks); } return jsonBuilder.build(); }
From source file:com.facebook.buck.config.BuckConfig.java
public Optional<ImmutableSet<PatternAndMessage>> getUnexpectedFlavorsMessages() { ImmutableMap<String, String> entries = config.get("unknown_flavors_messages"); if (!entries.isEmpty()) { Set<PatternAndMessage> patternAndMessages = new HashSet<>(); for (Map.Entry<String, String> entry : entries.entrySet()) { patternAndMessages.add(PatternAndMessage.of(Pattern.compile(entry.getKey()), entry.getValue())); }/* ww w .j ava 2s.c om*/ return Optional.of(ImmutableSet.copyOf(patternAndMessages)); } return Optional.empty(); }
From source file:org.apache.calcite.adapter.geode.rel.GeodeTable.java
/** * Executes an OQL query on the underlying table. * * <p>Called by the {@link GeodeQueryable} which in turn is * called via the generated code./* w w w. ja va 2s .c o m*/ * * @param clientCache Geode client cache * @param fields List of fields to project * @param predicates A list of predicates which should be used in the query * @return Enumerator of results */ public Enumerable<Object> query(final GemFireCache clientCache, final List<Map.Entry<String, Class>> fields, final List<Map.Entry<String, String>> selectFields, final List<Map.Entry<String, String>> aggregateFunctions, final List<String> groupByFields, List<String> predicates, List<String> orderByFields, Long limit) { final RelDataTypeFactory typeFactory = new JavaTypeFactoryExtImpl(); final RelDataTypeFactory.Builder fieldInfo = typeFactory.builder(); for (Map.Entry<String, Class> field : fields) { SqlTypeName typeName = typeFactory.createJavaType(field.getValue()).getSqlTypeName(); fieldInfo.add(field.getKey(), typeFactory.createSqlType(typeName)).nullable(true); } final RelProtoDataType resultRowType = RelDataTypeImpl.proto(fieldInfo.build()); ImmutableMap<String, String> aggFuncMap = ImmutableMap.of(); if (!aggregateFunctions.isEmpty()) { ImmutableMap.Builder<String, String> aggFuncMapBuilder = ImmutableMap.builder(); for (Map.Entry<String, String> e : aggregateFunctions) { aggFuncMapBuilder.put(e.getKey(), e.getValue()); } aggFuncMap = aggFuncMapBuilder.build(); } // Construct the list of fields to project Builder<String> selectBuilder = ImmutableList.builder(); if (!groupByFields.isEmpty()) { // manually add GROUP BY to select clause (GeodeProjection was not visited) for (String groupByField : groupByFields) { selectBuilder.add(groupByField + " AS " + groupByField); } if (!aggFuncMap.isEmpty()) { for (Map.Entry<String, String> e : aggFuncMap.entrySet()) { selectBuilder.add(e.getValue() + " AS " + e.getKey()); } } } else { if (selectFields.isEmpty()) { if (!aggFuncMap.isEmpty()) { for (Map.Entry<String, String> e : aggFuncMap.entrySet()) { selectBuilder.add(e.getValue() + " AS " + e.getKey()); } } else { selectBuilder.add("*"); } } else { if (!aggFuncMap.isEmpty()) { for (Map.Entry<String, String> e : aggFuncMap.entrySet()) { selectBuilder.add(e.getValue() + " AS " + e.getKey()); } } else { for (Map.Entry<String, String> field : selectFields) { selectBuilder.add(field.getKey() + " AS " + field.getValue()); } } } } final String oqlSelectStatement = Util.toString(selectBuilder.build(), "", ", ", ""); // Combine all predicates conjunctively String whereClause = ""; if (!predicates.isEmpty()) { whereClause = " WHERE "; whereClause += Util.toString(predicates, "", " AND ", ""); } // Build and issue the query and return an Enumerator over the results StringBuilder queryBuilder = new StringBuilder("SELECT "); queryBuilder.append(oqlSelectStatement); queryBuilder.append(" FROM /" + regionName); queryBuilder.append(whereClause); if (!groupByFields.isEmpty()) { queryBuilder.append(Util.toString(groupByFields, " GROUP BY ", ", ", "")); } if (!orderByFields.isEmpty()) { queryBuilder.append(Util.toString(orderByFields, " ORDER BY ", ", ", "")); } if (limit != null) { queryBuilder.append(" LIMIT " + limit); } final String oqlQuery = queryBuilder.toString(); Hook.QUERY_PLAN.run(oqlQuery); LOGGER.info("OQL: " + oqlQuery); return new AbstractEnumerable<Object>() { public Enumerator<Object> enumerator() { final QueryService queryService = clientCache.getQueryService(); try { SelectResults results = (SelectResults) queryService.newQuery(oqlQuery).execute(); return new GeodeEnumerator(results, resultRowType); } catch (Exception e) { String message = String.format(Locale.ROOT, "Failed to execute query [%s] on %s", oqlQuery, clientCache.getName()); throw new RuntimeException(message, e); } } }; }