List of usage examples for com.google.common.collect Sets newHashSetWithExpectedSize
public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize)
From source file:org.onosproject.net.topology.AbstractPathService.java
private Set<Path> edgeToEdgePaths(EdgeLink srcLink, EdgeLink dstLink, Set<Path> paths) { Set<Path> endToEndPaths = Sets.newHashSetWithExpectedSize(paths.size()); for (Path path : paths) { endToEndPaths.add(edgeToEdgePath(srcLink, dstLink, path)); }//from w ww .java 2 s. com return endToEndPaths; }
From source file:com.android.tools.idea.wizard.NewFormFactorModulePath.java
void updatePackageDerivedValues() { // TODO: Refactor handling of presets in TemplateParameterStep2 so that this isn't necessary myParameterStep.setPresetValue(PACKAGE_NAME_KEY.name, myState.get(PACKAGE_NAME_KEY)); Set<Key> keys = Sets.newHashSetWithExpectedSize(5); keys.add(PACKAGE_NAME_KEY);/*from w w w.ja va 2s . c o m*/ keys.add(SRC_DIR_KEY); keys.add(TEST_DIR_KEY); keys.add(PROJECT_LOCATION_KEY); keys.add(NUM_ENABLED_FORM_FACTORS_KEY); deriveValues(keys); }
From source file:com.google.javascript.jscomp.JsChecker.java
private boolean run() throws IOException { final JsCheckerState state = new JsCheckerState(label, legacy, testonly, roots, mysterySources); final Set<String> actuallySuppressed = new HashSet<>(); // read provided files created by this program on deps for (String dep : deps) { state.provided.addAll(JsCheckerHelper.loadClosureJsLibraryInfo(Paths.get(dep)).getNamespaceList()); }/*www .jav a 2s . c o m*/ Map<String, String> labels = new HashMap<>(); labels.put("", label); Set<String> modules = new LinkedHashSet<>(); for (String source : sources) { for (String module : convertPathToModuleName(source, state.roots).asSet()) { modules.add(module); labels.put(module, label); state.provides.add(module); } } for (String source : mysterySources) { for (String module : convertPathToModuleName(source, state.roots).asSet()) { checkArgument(!module.startsWith("blaze-out/"), "oh no: %s", state.roots); modules.add(module); state.provided.add(module); } } // configure compiler Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); options.setLanguage(LanguageMode.ECMASCRIPT_2017); options.setStrictModeInput(true); options.setIncrementalChecks(IncrementalCheckMode.GENERATE_IJS); options.setCodingConvention(convention.convention); options.setSkipTranspilationAndCrash(true); options.setContinueAfterErrors(true); options.setPrettyPrint(true); options.setPreserveTypeAnnotations(true); options.setPreserveDetailedSourceInfo(true); options.setEmitUseStrict(false); options.setParseJsDocDocumentation(Config.JsDocParsing.INCLUDE_DESCRIPTIONS_NO_WHITESPACE); JsCheckerErrorFormatter errorFormatter = new JsCheckerErrorFormatter(compiler, state.roots, labels); errorFormatter.setColorize(true); JsCheckerErrorManager errorManager = new JsCheckerErrorManager(errorFormatter); compiler.setErrorManager(errorManager); // configure which error messages appear if (!legacy) { for (String error : Iterables.concat(Diagnostics.JSCHECKER_ONLY_ERRORS, Diagnostics.JSCHECKER_EXTRA_ERRORS)) { options.setWarningLevel(Diagnostics.GROUPS.forName(error), CheckLevel.ERROR); } } final Set<DiagnosticType> suppressions = Sets.newHashSetWithExpectedSize(256); for (String code : suppress) { ImmutableSet<DiagnosticType> types = Diagnostics.getDiagnosticTypesForSuppressCode(code); if (types.isEmpty()) { System.err.println("ERROR: Bad --suppress value: " + code); return false; } suppressions.addAll(types); } options.addWarningsGuard(new WarningsGuard() { @Override public CheckLevel level(JSError error) { // TODO(jart): Figure out how to support this. if (error.getType().key.equals("JSC_CONSTANT_WITHOUT_EXPLICIT_TYPE")) { return CheckLevel.OFF; } // Closure Rules will always ignore these checks no matter what. if (Diagnostics.IGNORE_ALWAYS.contains(error.getType())) { return CheckLevel.OFF; } // Disable warnings specific to conventions other than the one we're using. if (!convention.diagnostics.contains(error.getType())) { for (JsCheckerConvention conv : JsCheckerConvention.values()) { if (!conv.equals(convention)) { if (conv.diagnostics.contains(error.getType())) { suppressions.add(error.getType()); return CheckLevel.OFF; } } } } // Disable warnings we've suppressed. Collection<String> groupNames = Diagnostics.DIAGNOSTIC_GROUPS.get(error.getType()); if (suppressions.contains(error.getType())) { actuallySuppressed.add(error.getType().key); actuallySuppressed.addAll(groupNames); return CheckLevel.OFF; } // Ignore linter warnings on generated sources. if (groupNames.contains("lintChecks") && JsCheckerHelper.isGeneratedPath(error.sourceName)) { return CheckLevel.OFF; } return null; } }); // Run the compiler. compiler.setPassConfig(new JsCheckerPassConfig(state, options)); compiler.disableThreads(); compiler.compile(ImmutableList.<SourceFile>of(), getSourceFiles(Iterables.concat(sources, mysterySources)), options); // In order for suppress to be maintainable, we need to make sure the suppress codes relating to // linting were actually suppressed. However we can only offer this safety on the checks over // which JsChecker has sole dominion. Other suppress codes won't actually be suppressed until // they've been propagated up to the closure_js_binary rule. if (!suppress.contains("superfluousSuppress")) { Set<String> useless = Sets.intersection( Sets.difference(ImmutableSet.copyOf(suppress), actuallySuppressed), Diagnostics.JSCHECKER_ONLY_SUPPRESS_CODES); if (!useless.isEmpty()) { errorManager.report(CheckLevel.ERROR, JSError.make(Diagnostics.SUPERFLUOUS_SUPPRESS, label, Joiner.on(", ").join(useless))); } } // TODO: Make compiler.compile() package private so we don't have to do this. errorManager.stderr.clear(); errorManager.generateReport(); // write errors if (!expectFailure) { for (String line : errorManager.stderr) { System.err.println(line); } } if (!outputErrors.isEmpty()) { Files.write(Paths.get(outputErrors), errorManager.stderr, UTF_8); } // write .i.js type summary for this library if (!outputIjsFile.isEmpty()) { Files.write(Paths.get(outputIjsFile), compiler.toSource().getBytes(UTF_8)); } // write file full of information about these sauces if (!output.isEmpty()) { ClosureJsLibrary.Builder info = ClosureJsLibrary.newBuilder().setLabel(label).setLegacy(legacy) .addAllNamespace(state.provides).addAllModule(modules); if (!legacy) { for (DiagnosticType suppression : suppressions) { if (!Diagnostics.JSCHECKER_ONLY_SUPPRESS_CODES.contains(suppression.key)) { info.addSuppress(suppression.key); } } } Files.write(Paths.get(output), info.build().toString().getBytes(UTF_8)); } return errorManager.getErrorCount() == 0; }
From source file:com.google.walkaround.util.server.appengine.MemcacheTable.java
public Map<K, V> getAll(Set<K> keys) { Set<TaggedKey<K>> taggedKeys = Sets.newHashSetWithExpectedSize(keys.size()); for (K key : keys) { taggedKeys.add(tagKey(key));//from w w w .ja va2 s.c o m } Map<TaggedKey<K>, Object> rawMappings; try { rawMappings = service.getAll(taggedKeys); } catch (InvalidValueException e) { // Probably a deserialization error (incompatible serialVersionUID or similar). log.log(Level.WARNING, "Error getting objects from memcache, keys: " + keys, e); return Collections.emptyMap(); } Map<K, V> mappings = Maps.newHashMapWithExpectedSize(rawMappings.size()); for (Map.Entry<TaggedKey<K>, Object> entry : rawMappings.entrySet()) { mappings.put(entry.getKey().getKey(), castRawValue(entry.getValue())); } log.info("Found " + mappings.size() + " of " + keys.size() + " objects in memcache: " + mappings); return mappings; }
From source file:org.graylog2.rest.resources.roles.RolesResource.java
@GET @Path("{rolename}/members") @RequiresPermissions({ RestPermissions.USERS_LIST, RestPermissions.ROLES_READ }) @ApiOperation(value = "Retrieve the role's members") public RoleMembershipResponse getMembers( @ApiParam(name = "rolename", required = true) @PathParam("rolename") String name) throws NotFoundException { final Role role = roleService.load(name); final Collection<User> users = userService.loadAllForRole(role); Set<UserSummary> userSummaries = Sets.newHashSetWithExpectedSize(users.size()); for (User user : users) { final Set<String> roleNames = userService.getRoleNames(user); userSummaries.add(UserSummary.create(user.getId(), user.getName(), user.getEmail(), user.getFullName(), isPermitted(RestPermissions.USERS_PERMISSIONSEDIT, user.getName()) ? userService.getPermissionsForUser(user) : Collections.<String>emptyList(), user.getPreferences(), firstNonNull(user.getTimeZone(), DateTimeZone.UTC).getID(), user.getSessionTimeoutMs(), user.isReadOnly(), user.isExternalUser(), user.getStartpage(), roleNames,/* w w w . j av a 2s. c om*/ // there is no session information available in this call, so we set it to null false, null, null)); } return RoleMembershipResponse.create(role.getName(), userSummaries); }
From source file:com.android.tools.lint.checks.DuplicateResourceDetector.java
@Override public void visitAttribute(@NonNull XmlContext context, @NonNull Attr attribute) { Element element = attribute.getOwnerElement(); if (element.hasAttribute(PRODUCT)) { return;/*from w w w. ja v a 2 s . c o m*/ } String tag = element.getTagName(); String typeString = tag; if (tag.equals(TAG_ITEM)) { typeString = element.getAttribute(ATTR_TYPE); if (typeString == null || typeString.isEmpty()) { if (element.getParentNode().getNodeName().equals(ResourceType.STYLE.getName()) && isFirstElementChild(element)) { checkUniqueNames(context, (Element) element.getParentNode()); } return; } } ResourceType type = ResourceType.getEnum(typeString); if (type == null) { return; } if (type == ResourceType.ATTR && element.getParentNode().getNodeName().equals(ResourceType.DECLARE_STYLEABLE.getName())) { if (isFirstElementChild(element)) { checkUniqueNames(context, (Element) element.getParentNode()); } return; } NodeList children = element.getChildNodes(); int childCount = children.getLength(); for (int i = 0; i < childCount; i++) { Node child = children.item(i); if (child.getNodeType() == Node.TEXT_NODE) { String text = child.getNodeValue(); for (int j = 0, length = text.length(); j < length; j++) { char c = text.charAt(j); if (c == '@') { if (!text.regionMatches(false, j + 1, typeString, 0, typeString.length()) && context.isEnabled(TYPE_MISMATCH)) { ResourceUrl url = ResourceUrl.parse(text.trim()); if (url != null && url.type != type && // colors and mipmaps can apparently be used as drawables !(type == ResourceType.DRAWABLE && (url.type == ResourceType.COLOR || url.type == ResourceType.MIPMAP))) { String message = "Unexpected resource reference type; " + "expected value of type `@" + type + "/`"; context.report(TYPE_MISMATCH, element, context.getLocation(child), message); } } break; } else if (!Character.isWhitespace(c)) { break; } } break; } } Set<String> names = mTypeMap.get(type); if (names == null) { names = Sets.newHashSetWithExpectedSize(40); mTypeMap.put(type, names); } String name = attribute.getValue(); String originalName = name; // AAPT will flatten the namespace, turning dots, dashes and colons into _ name = getResourceFieldName(name); if (names.contains(name)) { String message = String.format("`%1$s` has already been defined in this folder", name); if (!name.equals(originalName)) { message += " (`" + name + "` is equivalent to `" + originalName + "`)"; } Location location = context.getLocation(attribute); List<Pair<String, Handle>> list = mLocations.get(type); for (Pair<String, Handle> pair : list) { if (name.equals(pair.getFirst())) { Location secondary = pair.getSecond().resolve(); secondary.setMessage("Previously defined here"); location.setSecondary(secondary); } } context.report(ISSUE, attribute, location, message); } else { names.add(name); List<Pair<String, Handle>> list = mLocations.get(type); if (list == null) { list = Lists.newArrayList(); mLocations.put(type, list); } Location.Handle handle = context.createLocationHandle(attribute); list.add(Pair.of(name, handle)); } }
From source file:ch.silviowangler.dox.export.DoxExporterImpl.java
private Set<DocumentClass> processDocumentClasses(Set<ch.silviowangler.dox.api.DocumentClass> documentClasses) { Set<DocumentClass> docClasses = new HashSet<>(documentClasses.size()); for (ch.silviowangler.dox.api.DocumentClass documentClass : documentClasses) { logger.debug("Processing document class {}", documentClass); try {/*w w w.j a v a2 s.c om*/ SortedSet<ch.silviowangler.dox.api.Attribute> attributes = documentService .findAttributes(documentClass); Set<Attribute> exportAttributes = Sets.newHashSetWithExpectedSize(attributes.size()); for (ch.silviowangler.dox.api.Attribute attribute : attributes) { Attribute exportAttribute = new Attribute(); BeanUtils.copyProperties(attribute, exportAttribute, new String[] { "domain" }); if (attribute.containsDomain()) { Domain domain = new Domain(attribute.getDomain().getShortName()); for (String domainValue : attribute.getDomain().getValues()) { domain.getValues().add(domainValue); } exportAttribute.setDomain(domain); } exportAttributes.add(exportAttribute); } docClasses.add(new DocumentClass(exportAttributes, documentClass.getShortName())); } catch (DocumentClassNotFoundException e) { logger.error("Unexpected error. That document class must exist {}", documentClass, e); } } return docClasses; }
From source file:co.cask.tephra.snapshot.DefaultSnapshotCodec.java
private Set<ChangeId> decodeChanges(BinaryDecoder decoder) throws IOException { int size = decoder.readInt(); HashSet<ChangeId> changes = Sets.newHashSetWithExpectedSize(size); while (size != 0) { // zero denotes end of list as per AVRO spec for (int remaining = size; remaining > 0; --remaining) { changes.add(new ChangeId(decoder.readBytes())); }// www . j a va2s . com size = decoder.readInt(); } // todo is there an immutable hash set? return changes; }
From source file:org.eclipse.xtext.xbase.typesystem.override.RawResolvedFeatures.java
protected ListMultimap<String, JvmFeature> computeAllFeatures() { JvmType rawType = getRawType();//from w w w.j a va 2 s.c om if (!(rawType instanceof JvmDeclaredType)) { return ArrayListMultimap.create(); } ListMultimap<String, JvmFeature> result = ArrayListMultimap.create(); Multimap<String, AbstractResolvedOperation> processed = HashMultimap.create(); Set<String> processedFields = Sets.newHashSetWithExpectedSize(5); computeAllFeatures((JvmDeclaredType) rawType, processed, processedFields, result, featureIndex.keySet()); return Multimaps.unmodifiableListMultimap(result); }
From source file:com.google.devtools.build.lib.rules.genquery.GenQuery.java
private static Set<Target> getScope(RuleContext context) throws InterruptedException { List<Label> scopeLabels = context.attributes().get("scope", BuildType.LABEL_LIST); Set<Target> scope = Sets.newHashSetWithExpectedSize(scopeLabels.size()); for (Label scopePart : scopeLabels) { SkyFunction.Environment env = context.getAnalysisEnvironment().getSkyframeEnv(); PackageValue packageNode = (PackageValue) env .getValue(PackageValue.key(scopePart.getPackageIdentifier())); Preconditions.checkNotNull(packageNode, "Packages in transitive closure of scope '%s'" + "were already loaded during the loading phase", scopePart);/*ww w . ja v a 2 s.co m*/ try { scope.add(packageNode.getPackage().getTarget(scopePart.getName())); } catch (NoSuchTargetException e) { throw new IllegalStateException(e); } } return scope; }