List of usage examples for com.google.common.collect Sets newHashSetWithExpectedSize
public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize)
From source file:com.opengamma.financial.analytics.model.equity.option.ListedEquityOptionFunction.java
/** * Converts result properties with a currency property to one without. * /*from w ww .j a v a 2 s. co m*/ * @param resultsWithCurrency The set of results with the currency property set * @return A set of results without a currency property */ protected Set<ValueSpecification> getResultsWithoutCurrency(final Set<ValueSpecification> resultsWithCurrency) { final Set<ValueSpecification> resultsWithoutCurrency = Sets .newHashSetWithExpectedSize(resultsWithCurrency.size()); for (final ValueSpecification spec : resultsWithCurrency) { final String name = spec.getValueName(); final ComputationTargetSpecification targetSpec = spec.getTargetSpecification(); final ValueProperties properties = spec.getProperties().copy().withoutAny(ValuePropertyNames.CURRENCY) .get(); resultsWithoutCurrency.add(new ValueSpecification(name, targetSpec, properties)); } return resultsWithoutCurrency; }
From source file:com.android.build.gradle.tasks.ResourceUsageAnalyzer.java
private void keepPossiblyReferencedResources() { if ((!foundGetIdentifier && !foundWebContent) || strings == null) { // No calls to android.content.res.Resources#getIdentifier; no need // to worry about string references to resources return;//from w w w . j av a2s .c o m } if (!model.isSafeMode()) { // User specifically asked for us not to guess resources to keep; they will // explicitly mark them as kept if necessary instead return; } List<String> sortedStrings = new ArrayList<String>(strings); Collections.sort(sortedStrings); logger.fine("android.content.res.Resources#getIdentifier present: " + foundGetIdentifier); logger.fine("Web content present: " + foundWebContent); logger.fine("Referenced Strings:"); for (String string : sortedStrings) { string = string.trim().replace("\n", "\\n"); if (string.length() > 40) { string = string.substring(0, 37) + "..."; } else if (string.isEmpty()) { continue; } logger.fine(" " + string); } int shortest = Integer.MAX_VALUE; Set<String> names = Sets.newHashSetWithExpectedSize(50); for (Resource resource : model.getResources()) { String name = resource.name; names.add(name); int length = name.length(); if (length < shortest) { shortest = length; } } for (String string : strings) { if (string.length() < shortest) { continue; } // Check whether the string looks relevant // We consider four types of strings: // (1) simple resource names, e.g. "foo" from @layout/foo // These might be the parameter to a getIdentifier() call, or could // be composed into a fully qualified resource name for the getIdentifier() // method. We match these for *all* resource types. // (2) Relative source names, e.g. layout/foo, from @layout/foo // These might be composed into a fully qualified resource name for // getIdentifier(). // (3) Fully qualified resource names of the form package:type/name. // (4) If foundWebContent is true, look for android_res/ URL strings as well if (foundWebContent) { Resource resource = model.getResourceFromFilePath(string); if (resource != null) { ResourceUsageModel.markReachable(resource); continue; } else { int start = 0; int slash = string.lastIndexOf('/'); if (slash != -1) { start = slash + 1; } int dot = string.indexOf('.', start); String name = string.substring(start, dot != -1 ? dot : string.length()); if (names.contains(name)) { for (Map<String, Resource> map : model.getResourceMaps()) { resource = map.get(name); if (resource != null) { logger.fine( String.format("Marking %s used because it matches string pool constant %s", resource, string)); } ResourceUsageModel.markReachable(resource); } } } } // Look for normal getIdentifier resource URLs int n = string.length(); boolean justName = true; boolean formatting = false; boolean haveSlash = false; for (int i = 0; i < n; i++) { char c = string.charAt(i); if (c == '/') { haveSlash = true; justName = false; } else if (c == '.' || c == ':' || c == '%') { justName = false; if (c == '%') { formatting = true; } } else if (!Character.isJavaIdentifierPart(c)) { // This shouldn't happen; we've filtered out these strings in // the {@link #referencedString} method assert false : string; break; } } String name; if (justName) { // Check name (below) name = string; // Check for a simple prefix match, e.g. as in // getResources().getIdentifier("ic_video_codec_" + codecName, "drawable", ...) for (Resource resource : model.getResources()) { if (resource.name.startsWith(name)) { logger.fine( String.format("Marking %s used because its prefix matches string pool constant %s", resource, string)); ResourceUsageModel.markReachable(resource); } } } else if (!haveSlash) { if (formatting) { // Possibly a formatting string, e.g. // String name = String.format("my_prefix_%1d", index); // int res = getContext().getResources().getIdentifier(name, "drawable", ...) try { Pattern pattern = Pattern.compile(convertFormatStringToRegexp(string)); for (Resource resource : model.getResources()) { if (pattern.matcher(resource.name).matches()) { logger.fine(String.format( "Marking %s used because it format-string matches string pool constant %s", resource, string)); ResourceUsageModel.markReachable(resource); } } } catch (PatternSyntaxException ignored) { // Might not have been a formatting string after all! } } // If we have more than just a symbol name, we expect to also see a slash //noinspection UnnecessaryContinue continue; } else { // Try to pick out the resource name pieces; if we can find the // resource type unambiguously; if not, just match on names int slash = string.indexOf('/'); assert slash != -1; // checked with haveSlash above name = string.substring(slash + 1); if (name.isEmpty() || !names.contains(name)) { continue; } // See if have a known specific resource type if (slash > 0) { int colon = string.indexOf(':'); String typeName = string.substring(colon != -1 ? colon + 1 : 0, slash); ResourceType type = ResourceType.getEnum(typeName); if (type == null) { continue; } Resource resource = model.getResource(type, name); if (resource != null) { logger.fine(String.format("Marking %s used because it matches string pool constant %s", resource, string)); } ResourceUsageModel.markReachable(resource); continue; } // fall through and check the name } if (names.contains(name)) { for (Map<String, Resource> map : model.getResourceMaps()) { Resource resource = map.get(name); if (resource != null) { logger.fine(String.format("Marking %s used because it matches string pool constant %s", resource, string)); } ResourceUsageModel.markReachable(resource); } } else if (Character.isDigit(name.charAt(0))) { // Just a number? There are cases where it calls getIdentifier by // a String number; see for example SuggestionsAdapter in the support // library which reports supporting a string like "2130837524" and // "android.resource://com.android.alarmclock/2130837524". try { int id = Integer.parseInt(name); if (id != 0) { ResourceUsageModel.markReachable(model.getResource(id)); } } catch (NumberFormatException e) { // pass } } } }
From source file:org.sosy_lab.cpachecker.util.VariableClassificationBuilder.java
/** This function handles a declaration with an optional initializer. * Only simple types are handled. */ private void handleDeclarationEdge(final CDeclarationEdge edge) throws UnrecognizedCCodeException { CDeclaration declaration = edge.getDeclaration(); if (!(declaration instanceof CVariableDeclaration)) { return;//from w ww . j a v a 2 s.com } CVariableDeclaration vdecl = (CVariableDeclaration) declaration; String varName = vdecl.getQualifiedName(); allVars.add(varName); // "connect" the edge with its partition Set<String> var = Sets.newHashSetWithExpectedSize(1); var.add(varName); dependencies.addAll(var, new HashSet<BigInteger>(), edge, 0); // only simple types (int, long) are allowed for booleans, ... if (!(vdecl.getType() instanceof CSimpleType)) { nonIntBoolVars.add(varName); nonIntEqVars.add(varName); nonIntAddVars.add(varName); } final CInitializer initializer = vdecl.getInitializer(); List<CExpressionAssignmentStatement> l = CInitializers.convertToAssignments(vdecl, edge); for (CExpressionAssignmentStatement init : l) { final CLeftHandSide lhsExpression = init.getLeftHandSide(); final VariableOrField lhs = lhsExpression.accept(collectingLHSVisitor); final CExpression rhs = init.getRightHandSide(); rhs.accept(new CollectingRHSVisitor(lhs)); } if ((initializer == null) || !(initializer instanceof CInitializerExpression)) { return; } CExpression exp = ((CInitializerExpression) initializer).getExpression(); if (exp == null) { return; } handleExpression(edge, exp, varName, VariableOrField.newVariable(varName)); }
From source file:org.n52.sos.encode.SensorMLEncoderv101.java
private void addAbstractProcessValues(final AbstractProcessType abstractProcess, final AbstractProcess sosAbstractProcess) throws OwsExceptionReport { if (sosAbstractProcess.isSetGmlId()) { abstractProcess.setId(sosAbstractProcess.getGmlId()); }// w w w . j av a2 s . c om addSpecialCapabilities(sosAbstractProcess); if (sosAbstractProcess.isSetCapabilities()) { final Capabilities[] existing = abstractProcess.getCapabilitiesArray(); final Set<String> names = Sets.newHashSetWithExpectedSize(existing.length); for (final Capabilities element : existing) { if (element.getName() != null) { names.add(element.getName()); } } for (final SmlCapabilities sosCapability : sosAbstractProcess.getCapabilities()) { final Capabilities c = createCapability(sosCapability); // replace existing capability with the same name if (names.contains(c.getName())) { removeCapability(abstractProcess, c); } abstractProcess.addNewCapabilities().set(c); } } // set description if (sosAbstractProcess.isSetDescription() && !abstractProcess.isSetDescription()) { abstractProcess.addNewDescription().setStringValue(sosAbstractProcess.getDescription()); } if (sosAbstractProcess.isSetName() && CollectionHelper.isNullOrEmpty(abstractProcess.getNameArray())) { // TODO check if override existing names addNamesToAbstractProcess(abstractProcess, sosAbstractProcess.getNames()); } // set identification if (sosAbstractProcess.isSetIdentifications()) { abstractProcess.setIdentificationArray(createIdentification(sosAbstractProcess.getIdentifications())); } // set classification if (sosAbstractProcess.isSetClassifications()) { abstractProcess.setClassificationArray(createClassification(sosAbstractProcess.getClassifications())); } // set characteristics if (sosAbstractProcess.isSetCharacteristics()) { abstractProcess.setCharacteristicsArray(createCharacteristics(sosAbstractProcess.getCharacteristics())); } // set documentation if (sosAbstractProcess.isSetDocumentation()) { abstractProcess.setDocumentationArray(createDocumentationArray(sosAbstractProcess.getDocumentation())); } // set contacts if contacts aren't already present in the abstract // process if (sosAbstractProcess.isSetContact() && (abstractProcess.getContactArray() == null || abstractProcess.getContactArray().length == 0)) { ContactList contactList = createContactList(sosAbstractProcess.getContact()); if (contactList != null && contactList.getMemberArray().length > 0) { abstractProcess.addNewContact().setContactList(contactList); } } // set keywords if (sosAbstractProcess.isSetKeywords()) { final List<String> keywords = sosAbstractProcess.getKeywords(); final int length = abstractProcess.getKeywordsArray().length; for (int i = 0; i < length; ++i) { abstractProcess.removeKeywords(i); } abstractProcess.addNewKeywords().addNewKeywordList() .setKeywordArray(keywords.toArray(new String[keywords.size()])); } if (sosAbstractProcess.isSetValidTime()) { if (abstractProcess.isSetValidTime()) { // remove existing validTime element final XmlCursor newCursor = abstractProcess.getValidTime().newCursor(); newCursor.removeXml(); newCursor.dispose(); } final Time time = sosAbstractProcess.getValidTime(); final XmlObject xbtime = CodingHelper.encodeObjectToXml(GmlConstants.NS_GML, time); if (time instanceof TimeInstant) { abstractProcess.addNewValidTime().addNewTimeInstant().set(xbtime); } else if (time instanceof TimePeriod) { abstractProcess.addNewValidTime().addNewTimePeriod().set(xbtime); } } }
From source file:de.devsurf.components.cmis.RepositoryService.java
/** * Gathers all base properties of a file or folder. *//*from w ww .ja v a2s .com*/ private Properties compileProperties(SaClassicConnector connector, SaDocumentInfo info, String parent, ObjectInfoImpl objectInfo) { if (info == null) { throw new IllegalArgumentException("Item must not be null!"); } Set<String> filter = Sets.newHashSetWithExpectedSize(0); objectInfo.setBaseType(BaseTypeId.CMIS_DOCUMENT); objectInfo.setTypeId(BaseTypeId.CMIS_DOCUMENT.value()); objectInfo.setHasAcl(false); objectInfo.setHasContent(true); objectInfo.setHasParent(false); objectInfo.setVersionSeriesId(null); objectInfo.setIsCurrentVersion(true); objectInfo.setRelationshipSourceIds(null); objectInfo.setRelationshipTargetIds(null); objectInfo.setRenditionInfos(null); objectInfo.setSupportsDescendants(false); objectInfo.setSupportsFolderTree(false); objectInfo.setSupportsPolicies(false); objectInfo.setSupportsRelationships(false); objectInfo.setWorkingCopyId(null); objectInfo.setWorkingCopyOriginalId(null); // find base type String typeId = null; // let's do it try { PropertiesImpl result = new PropertiesImpl(); // id String id = info.getValue("SYSROWID").getStringValue();// add null // check addPropertyId(result, typeId, filter, PropertyIds.OBJECT_ID, id); objectInfo.setId(id); String versionId = info.getValue("XHDOC").getStringValue(); addPropertyId(result, typeId, filter, PropertyIds.VERSION_SERIES_ID, versionId); objectInfo.setVersionSeriesId(versionId); // name String name = info.getValue("NAME").getStringValue();// add null // check, addPropertyString(result, typeId, filter, PropertyIds.NAME, name); objectInfo.setName(name); // created and modified by String username = info.getValue("SYSMODIFYUSER").getStringValue(); // add // null // check addPropertyString(result, typeId, filter, PropertyIds.CREATED_BY, username); // switch to SYSCREATEUSER addPropertyString(result, typeId, filter, PropertyIds.LAST_MODIFIED_BY, username); objectInfo.setCreatedBy(username); // creation and modification date GregorianCalendar lastModified = millisToCalendar(System.currentTimeMillis()); addPropertyDateTime(result, typeId, filter, PropertyIds.CREATION_DATE, lastModified); // SYSCREATEDATE addPropertyDateTime(result, typeId, filter, PropertyIds.LAST_MODIFICATION_DATE, lastModified); // SYSTIMESTAMP objectInfo.setCreationDate(lastModified); objectInfo.setLastModificationDate(lastModified); // change token - always null addPropertyString(result, typeId, filter, PropertyIds.CHANGE_TOKEN, null); // CMIS 1.1 properties addPropertyString(result, typeId, filter, PropertyIds.DESCRIPTION, null); addPropertyIdList(result, typeId, filter, PropertyIds.SECONDARY_OBJECT_TYPE_IDS, null); // base type and type name addPropertyId(result, typeId, filter, PropertyIds.BASE_TYPE_ID, BaseTypeId.CMIS_DOCUMENT.value()); // ? addPropertyId(result, typeId, filter, PropertyIds.OBJECT_TYPE_ID, BaseTypeId.CMIS_DOCUMENT.value()); // ? // file properties addPropertyBoolean(result, typeId, filter, PropertyIds.IS_IMMUTABLE, false); addPropertyBoolean(result, typeId, filter, PropertyIds.IS_LATEST_VERSION, true); addPropertyBoolean(result, typeId, filter, PropertyIds.IS_MAJOR_VERSION, true); addPropertyBoolean(result, typeId, filter, PropertyIds.IS_LATEST_MAJOR_VERSION, true); addPropertyString(result, typeId, filter, PropertyIds.VERSION_LABEL, name); addPropertyId(result, typeId, filter, PropertyIds.VERSION_SERIES_ID, versionId); // ? addPropertyBoolean(result, typeId, filter, PropertyIds.IS_VERSION_SERIES_CHECKED_OUT, false); addPropertyString(result, typeId, filter, PropertyIds.VERSION_SERIES_CHECKED_OUT_BY, null); addPropertyString(result, typeId, filter, PropertyIds.VERSION_SERIES_CHECKED_OUT_ID, null); addPropertyString(result, typeId, filter, PropertyIds.CHECKIN_COMMENT, ""); SaDocInfo contentInfos = connector.getDocumentInfo(versionId, false, true); if (contentInfos.getElementCount() == 0) { addPropertyBigInteger(result, typeId, filter, PropertyIds.CONTENT_STREAM_LENGTH, null); addPropertyString(result, typeId, filter, PropertyIds.CONTENT_STREAM_MIME_TYPE, null); addPropertyString(result, typeId, filter, PropertyIds.CONTENT_STREAM_FILE_NAME, null); addPropertyId(result, typeId, filter, PropertyIds.CONTENT_STREAM_ID, null); objectInfo.setHasContent(false); objectInfo.setContentType(null); objectInfo.setFileName(null); } else { ElementInfo contentInfo = contentInfos.getElementInfo(1); addPropertyInteger(result, typeId, filter, PropertyIds.CONTENT_STREAM_LENGTH, contentInfo.getSize()); String contentFilename = contentInfo.getName(); String contentMimeType = MimeTypes.getMIMEType(contentFilename); addPropertyString(result, typeId, filter, PropertyIds.CONTENT_STREAM_MIME_TYPE, contentMimeType); addPropertyString(result, typeId, filter, PropertyIds.CONTENT_STREAM_FILE_NAME, contentFilename); addPropertyId(result, typeId, filter, PropertyIds.CONTENT_STREAM_ID, contentInfo.getDocUid()); objectInfo.setHasContent(true); objectInfo.setContentType(contentMimeType); objectInfo.setFileName(contentFilename); } return result; } catch (Exception e) { if (e instanceof CmisBaseException) { throw (CmisBaseException) e; } throw new CmisRuntimeException(e.getMessage(), e); } }
From source file:com.opengamma.financial.analytics.timeseries.HistoricalValuationFunction.java
@Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final HistoricalViewEvaluationResult evaluationResult = (HistoricalViewEvaluationResult) inputs .getValue(ValueRequirementNames.HISTORICAL_TIME_SERIES); final Set<ComputedValue> results = Sets.newHashSetWithExpectedSize(desiredValues.size()); final ComputationTargetSpecification targetSpec = target.toSpecification(); for (final ValueRequirement desiredValue : desiredValues) { final ValueRequirement requirement = getNestedRequirement( executionContext.getComputationTargetResolver(), target, desiredValue.getConstraints()); if (requirement != null) { @SuppressWarnings("rawtypes") final TimeSeries ts = evaluationResult.getTimeSeries(requirement); if (ts != null) { results.add(new ComputedValue(new ValueSpecification(desiredValue.getValueName(), targetSpec, desiredValue.getConstraints()), ts)); } else { s_logger.warn("Nested requirement {} did not produce a time series for {}", requirement, desiredValue);/* w w w. j av a2 s .com*/ } } else { s_logger.error("Couldn't produce nested requirement for {}", desiredValue); } } return results; }
From source file:com.google.gerrit.server.change.ChangeJson.java
private Collection<AccountInfo> removableReviewers(ChangeData cd, Collection<LabelInfo> labels) throws OrmException { ChangeControl ctl = control(cd);/*from w ww . j a v a 2 s. c o m*/ if (ctl == null) { return null; } Set<Account.Id> fixed = Sets.newHashSetWithExpectedSize(labels.size()); Set<Account.Id> removable = Sets.newHashSetWithExpectedSize(labels.size()); for (LabelInfo label : labels) { if (label.all == null) { continue; } for (ApprovalInfo ai : label.all) { if (ctl.canRemoveReviewer(ai._id, Objects.firstNonNull(ai.value, 0))) { removable.add(ai._id); } else { fixed.add(ai._id); } } } removable.removeAll(fixed); List<AccountInfo> result = Lists.newArrayListWithCapacity(removable.size()); for (Account.Id id : removable) { result.add(accountLoader.get(id)); } return result; }
From source file:org.n52.sos.util.GeometryHandler.java
public Set<String> addAuthorityCrsPrefix(Collection<Integer> crses) { HashSet<String> withPrefix = Sets.newHashSetWithExpectedSize(crses.size()); for (Integer crs : crses) { withPrefix.add(addAuthorityCrsPrefix(crs)); }/*w w w . j av a 2 s. c o m*/ return withPrefix; }
From source file:org.n52.sos.util.GeometryHandler.java
public Set<String> addOgcCrsPrefix(Collection<Integer> crses) { HashSet<String> withPrefix = Sets.newHashSetWithExpectedSize(crses.size()); for (Integer crs : crses) { withPrefix.add(addOgcCrsPrefix(crs)); }/*from w ww . j a v a 2s .com*/ return withPrefix; }
From source file:com.android.tools.lint.checks.SupportAnnotationDetector.java
private PermissionHolder getPermissions(@NonNull JavaContext context) { if (mPermissions == null) { Set<String> permissions = Sets.newHashSetWithExpectedSize(30); Set<String> revocable = Sets.newHashSetWithExpectedSize(4); LintClient client = context.getClient(); // Gather permissions from all projects that contribute to the // main project. Project mainProject = context.getMainProject(); for (File manifest : mainProject.getManifestFiles()) { addPermissions(client, permissions, revocable, manifest); }//from w ww . ja va 2 s .c om for (Project library : mainProject.getAllLibraries()) { for (File manifest : library.getManifestFiles()) { addPermissions(client, permissions, revocable, manifest); } } AndroidVersion minSdkVersion = mainProject.getMinSdkVersion(); AndroidVersion targetSdkVersion = mainProject.getTargetSdkVersion(); mPermissions = new SetPermissionLookup(permissions, revocable, minSdkVersion, targetSdkVersion); } return mPermissions; }