List of usage examples for com.google.common.collect SetMultimap put
boolean put(@Nullable K key, @Nullable V value);
From source file:org.opendaylight.yangtools.yang.model.util.FilteringSchemaContextProxy.java
/** * Filters SchemaContext for yang modules * * @param delegate original SchemaContext * @param rootModules modules (yang schemas) to be available and all their dependencies (modules importing rootModule and whole chain of their imports) * @param additionalModuleIds (additional) modules (yang schemas) to be available and whole chain of their imports * *///from w w w. j a v a 2s.co m public FilteringSchemaContextProxy(final SchemaContext delegate, final Collection<ModuleId> rootModules, final Set<ModuleId> additionalModuleIds) { Preconditions.checkArgument(rootModules != null, "Base modules cannot be null."); Preconditions.checkArgument(additionalModuleIds != null, "Additional modules cannot be null."); final Builder<Module> filteredModulesBuilder = new Builder<>(); final SetMultimap<URI, Module> nsMap = Multimaps.newSetMultimap(new TreeMap<>(), MODULE_SET_SUPPLIER); final SetMultimap<String, Module> nameMap = Multimaps.newSetMultimap(new TreeMap<>(), MODULE_SET_SUPPLIER); ImmutableMap.Builder<ModuleIdentifier, String> identifiersToSourcesBuilder = ImmutableMap.builder(); //preparing map to get all modules with one name but difference in revision final TreeMultimap<String, Module> nameToModulesAll = getStringModuleTreeMultimap(); nameToModulesAll.putAll(getStringModuleMap(delegate)); //in case there is a particular dependancy to view filteredModules/yang models //dependancy is checked for module name and imports processForRootModules(delegate, rootModules, filteredModulesBuilder); //adding additional modules processForAdditionalModules(delegate, additionalModuleIds, filteredModulesBuilder); filteredModulesBuilder.addAll( getImportedModules(Maps.uniqueIndex(delegate.getModules(), ModuleId.MODULE_TO_MODULE_ID::apply), filteredModulesBuilder.build(), nameToModulesAll)); /** * Instead of doing this on each invocation of getModules(), pre-compute * it once and keep it around -- better than the set we got in. */ this.filteredModules = filteredModulesBuilder.build(); for (final Module module : filteredModules) { nameMap.put(module.getName(), module); nsMap.put(module.getNamespace(), module); identifiersToSourcesBuilder.put(module, module.getSource()); } namespaceToModules = ImmutableSetMultimap.copyOf(nsMap); nameToModules = ImmutableSetMultimap.copyOf(nameMap); identifiersToSources = identifiersToSourcesBuilder.build(); }
From source file:de.bund.bfr.knime.gis.views.canvas.Canvas.java
@Override public void collapseByPropertyItemClicked() { Set<String> selectedIds = CanvasUtils.getElementIds(getSelectedNodes()); Set<String> idsToCollapse; if (!selectedIds.isEmpty()) { switch (Dialogs.showYesNoCancelDialog(this, "Use only the selected " + naming.nodes() + " for collapsing?", "Confirm")) { case YES: idsToCollapse = selectedIds; break; case NO:/*from w ww. j av a 2s . c om*/ idsToCollapse = CanvasUtils.getElementIds(getNodes()); break; case CANCEL: default: return; } } else { idsToCollapse = CanvasUtils.getElementIds(getNodes()); } for (String id : idsToCollapse) { if (collapsedNodes.keySet().contains(id)) { String message; if (idsToCollapse == selectedIds) { message = "Some of the selected " + naming.nodes() + " are already collapsed."; } else { message = "Some of the " + naming.nodes() + " are already collapsed. You have to clear all collapsed " + naming.nodes() + " before."; } Dialogs.showErrorMessage(this, message); return; } } String result = Dialogs.showInputDialog(this, "Select Property for Collapse?", "Collapse by Property", nodeSchema.getMap().keySet()); if (result == null) { return; } SetMultimap<Object, V> nodesByProperty = LinkedHashMultimap.create(); for (String id : idsToCollapse) { V node = nodeSaveMap.get(id); Object value = node.getProperties().get(result); if (value != null) { nodesByProperty.put(value, node); } } ListFilterDialog<Object> dialog = new ListFilterDialog<>(this, KnimeUtils.ORDERING.sortedCopy(nodesByProperty.keySet())); dialog.setVisible(true); if (!dialog.isApproved() || dialog.getFiltered().isEmpty()) { return; } nodesByProperty.keySet().retainAll(dialog.getFiltered()); Set<String> newCollapsedIds = new LinkedHashSet<>(); Multimaps.asMap(nodesByProperty).forEach((property, nodes) -> { String newId = KnimeUtils.createNewValue(property.toString(), nodeSaveMap.keySet()); collapsedNodes.put(newId, CanvasUtils.getElementIds(nodes)); newCollapsedIds.add(newId); }); applyChanges(); setSelectedNodeIdsWithoutListener(newCollapsedIds); call(l -> l.collapsedNodesAndPickingChanged(this)); }
From source file:omero.cmd.graphs.DiskUsageI.java
/** * Calculate the disk usage of the model objects specified in the request. * @return the total usage, in bytes// w w w. ja va 2 s .c o m */ private DiskUsageResponse getDiskUsage() { final IQuery queryService = helper.getServiceFactory().getQueryService(); final int batchSize = 256; final SetMultimap<String, Long> objectsToProcess = HashMultimap.create(); final SetMultimap<String, Long> objectsProcessed = HashMultimap.create(); final Usage usage = new Usage(); /* original file ID to types that refer to them */ final SetMultimap<Long, String> typesWithFiles = HashMultimap.create(); /* original file ID to file ownership and size */ final Map<Long, OwnershipAndSize> fileSizes = new HashMap<Long, OwnershipAndSize>(); /* note the objects to process */ for (final String className : classes) { final String hql = "SELECT " + getIdPropertyFor(className) + " FROM " + className; for (final Object[] resultRow : queryService.projection(hql, null)) { if (resultRow != null) { final Long objectId = (Long) resultRow[0]; objectsToProcess.put(className, objectId); } } } for (final Map.Entry<String, List<Long>> objectList : objects.entrySet()) { objectsToProcess.putAll(objectList.getKey(), objectList.getValue()); if (LOGGER.isDebugEnabled()) { final List<Long> ids = Lists.newArrayList(objectsToProcess.get(objectList.getKey())); Collections.sort(ids); LOGGER.debug("size calculator to process " + objectList.getKey() + " " + Joiner.on(", ").join(ids)); } } /* check that the objects' class names are valid */ for (final String className : objectsToProcess.keySet()) { getIdPropertyFor(className); } /* iteratively process objects, descending the model graph */ while (!objectsToProcess.isEmpty()) { /* obtain canonical class name and ID list */ final Map.Entry<String, Collection<Long>> nextClass = objectsToProcess.asMap().entrySet().iterator() .next(); String className = nextClass.getKey(); final int lastDot = className.lastIndexOf('.'); if (lastDot >= 0) { className = className.substring(lastDot + 1); } else if (className.charAt(0) == '/') { className = className.substring(1); } /* get IDs still to process, and split off a batch of them for this query */ final Collection<Long> ids = nextClass.getValue(); ids.removeAll(objectsProcessed.get(className)); if (ids.isEmpty()) { continue; } final List<Long> idsToQuery = Lists.newArrayList(Iterables.limit(ids, batchSize)); ids.removeAll(idsToQuery); objectsProcessed.putAll(className, idsToQuery); final Parameters parameters = new Parameters().addIds(idsToQuery); if ("Pixels".equals(className)) { /* Pixels may have /OMERO/Pixels/<id> files */ final String hql = "SELECT id, details.owner.id, details.group.id FROM Pixels WHERE id IN (:ids)"; for (final Object[] resultRow : queryService.projection(hql, parameters)) { if (resultRow != null) { final Long pixelsId = (Long) resultRow[0]; final Long ownerId = (Long) resultRow[1]; final Long groupId = (Long) resultRow[2]; final String pixelsPath = pixelsService.getPixelsPath(pixelsId); usage.bumpTotals().add(ownerId, groupId, className, getFileSize(pixelsPath)); usage.bumpTotals().add(ownerId, groupId, className, getFileSize(pixelsPath + PixelsService.PYRAMID_SUFFIX)); usage.bumpTotals().add(ownerId, groupId, className, getFileSize( pixelsPath + PixelsService.PYRAMID_SUFFIX + BfPyramidPixelBuffer.PYR_LOCK_EXT)); } } } else if ("Thumbnail".equals(className)) { /* Thumbnails may have /OMERO/Thumbnails/<id> files */ final String hql = "SELECT id, details.owner.id, details.group.id FROM Thumbnail WHERE id IN (:ids)"; for (final Object[] resultRow : queryService.projection(hql, parameters)) { if (resultRow != null) { final Long thumbnailId = (Long) resultRow[0]; final Long ownerId = (Long) resultRow[1]; final Long groupId = (Long) resultRow[2]; final String thumbnailPath = thumbnailService.getThumbnailPath(thumbnailId); usage.bumpTotals().add(ownerId, groupId, className, getFileSize(thumbnailPath)); } } } else if ("OriginalFile".equals(className)) { /* OriginalFiles have their size noted */ final String hql = "SELECT id, details.owner.id, details.group.id, size FROM OriginalFile WHERE id IN (:ids)"; for (final Object[] resultRow : queryService.projection(hql, parameters)) { if (resultRow != null && resultRow[3] instanceof Long) { final Long fileId = (Long) resultRow[0]; final Long ownerId = (Long) resultRow[1]; final Long groupId = (Long) resultRow[2]; final Long fileSize = (Long) resultRow[3]; fileSizes.put(fileId, new OwnershipAndSize(ownerId, groupId, fileSize)); } } } else if ("Experimenter".equals(className)) { /* for an experimenter, use the list of owned objects */ for (final String resultClassName : OWNED_OBJECTS) { final String hql = "SELECT " + getIdPropertyFor(resultClassName) + " FROM " + resultClassName + " WHERE details.owner.id IN (:ids)"; for (final Object[] resultRow : queryService.projection(hql, parameters)) { objectsToProcess.put(resultClassName, (Long) resultRow[0]); } } } else if ("ExperimenterGroup".equals(className)) { /* for an experimenter group, use the list of owned objects */ for (final String resultClassName : OWNED_OBJECTS) { final String hql = "SELECT " + getIdPropertyFor(resultClassName) + " FROM " + resultClassName + " WHERE details.group.id IN (:ids)"; for (final Object[] resultRow : queryService.projection(hql, parameters)) { objectsToProcess.put(resultClassName, (Long) resultRow[0]); } } } /* follow the next step from here on the model object graph */ for (final Map.Entry<String, String> query : TRAVERSAL_QUERIES.get(className)) { final String resultClassName = query.getKey(); final String hql = query.getValue(); for (final Object[] resultRow : queryService.projection(hql, parameters)) { if (resultRow != null && resultRow[0] instanceof Long) { final Long resultId = (Long) resultRow[0]; objectsToProcess.put(resultClassName, resultId); if ("OriginalFile".equals(resultClassName)) { typesWithFiles.put(resultId, className); } } } } if (ANNOTATABLE_OBJECTS.contains(className)) { /* also watch for annotations on the current objects */ final String hql = "SELECT child.id FROM " + className + "AnnotationLink WHERE parent.id IN (:ids)"; for (final Object[] resultRow : queryService.projection(hql, parameters)) { objectsToProcess.put("Annotation", (Long) resultRow[0]); } } if (LOGGER.isDebugEnabled()) { Collections.sort(idsToQuery); LOGGER.debug("usage is " + usage + " after processing " + className + " " + Joiner.on(", ").join(idsToQuery)); } } /* collate file counts and sizes by referer type */ for (final Map.Entry<Long, OwnershipAndSize> fileIdSize : fileSizes.entrySet()) { final Long fileId = fileIdSize.getKey(); final OwnershipAndSize fileSize = fileIdSize.getValue(); Set<String> types = typesWithFiles.get(fileId); if (types.isEmpty()) { types = ImmutableSet.of("OriginalFile"); } usage.bumpTotals(); for (final String type : types) { usage.add(fileSize.owner, fileSize.group, type, fileSize.size); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("usage is " + usage + " after including " + OriginalFile.class.getSimpleName() + " sizes"); } return usage.getDiskUsageResponse(); }
From source file:co.mitro.core.servlets.ListMySecretsAndGroupKeys.java
/** * This gets all secrets accessible from any of the groups provided * @param context request context/*from ww w .j a v a2 s . c o m*/ * @param topLevel Should we include secrets that we have access to only via a top level group? * @param stopwatch used for timing things (maybe we should elminate this?) * @param secretToPath output value: returns a map of secret ID to secret + list of group ids used to access the secret * @param groupIds list of groups to search for secrets * @param secretIdsToExclude any secrets we should not include in the response, if not null. * @param auditLogInfo Should we include audit log info in the responses? * @return a set of secret ids we've examined * @throws MitroServletException * @throws SQLException * @throws DoEmailVerificationException WTF? */ static Set<Integer> getSecretInfo(MitroRequestContext context, AdminAccess topLevel, Map<Integer, SecretToPath> secretToPath, Set<Integer> groupIds, Set<Integer> secretIdsToExclude, IncludeAuditLogInfo auditLogInfo) throws MitroServletException, SQLException, DoEmailVerificationException { Set<Integer> rval = Sets.newHashSet(); final class GetSecretsResultType { int relatedSecretId; int ownSecretId; boolean autoDelete; int groupId; Integer aclMemberId; Integer aclGroupId; String aclMemberEmail; String aclGroupName; int secretId; String encryptedClientData; boolean isViewable; String kingName; boolean isTopLevel; } String groupIdString = Joiner.on(",").join(groupIds); if (groupIds.isEmpty()) { // this should never happen; probably only in the regression test. throw new MitroServletException("User without any groups; WTF?"); } String getSecretsStatement = "SELECT DISTINCT " + "all_secret.id as related_secret_id, " + "one_secret.id as initial_secret_id, " + "groups.\"autoDelete\", " + "groups.id as group_id, " + "acl.member_identity," + "acl.group_identity, " + "identity.name, " + "secrets.id AS secretId, " + "all_secret.\"clientVisibleDataEncrypted\" as encrypted_client_data, " + "org_group.name as org_group_name, " + "secrets.is_viewable as is_viewable, " + "king_identity.name, " + IS_TOPLEVEL_ORG_QUERY_PIECE + " as is_org " + "FROM " + "group_secret as one_secret, " + "group_secret as all_secret, " + "secrets " + "LEFT OUTER JOIN " + "identity AS king_identity ON secrets.king = king_identity.id, " + "groups, " + "acl " + "LEFT OUTER JOIN " + "identity on acl.member_identity = identity.id " + "LEFT OUTER JOIN " + "groups as org_group on acl.group_identity = org_group.id " + "WHERE " + "all_secret.\"serverVisibleSecret_id\" = one_secret.\"serverVisibleSecret_id\" " + "AND " + "all_secret.group_id = groups.id " + "AND " + "acl.group_id = all_secret.group_id " + "AND " + "secrets.id = all_secret.\"serverVisibleSecret_id\" " + "AND " + "one_secret.group_id in (" + groupIdString + ")"; if (topLevel.equals(AdminAccess.IGNORE_ACCESS_VIA_TOPLEVEL_GROUPS)) { getSecretsStatement += " AND NOT " + IS_TOPLEVEL_ORG_QUERY_PIECE; } else if (topLevel.equals(AdminAccess.FORCE_ACCESS_VIA_TOPLEVEL_GROUPS)) { // SQL hacking: order by sorts false before true. You have to check null explicitly. // ensuring that top level orgs appear before other groups ensures that // the secret is always mapped to top level orgs. getSecretsStatement += " ORDER BY " + IS_TOPLEVEL_ORG_QUERY_PIECE + " DESC"; } List<GetSecretsResultType> results = Lists.newArrayList( context.manager.groupDao.queryRaw(getSecretsStatement, new RawRowMapper<GetSecretsResultType>() { public GetSecretsResultType mapRow(String[] columnNames, String[] resultColumns) { GetSecretsResultType rval = new GetSecretsResultType(); rval.relatedSecretId = Integer.parseInt(resultColumns[0]); rval.ownSecretId = Integer.parseInt(resultColumns[1]); rval.autoDelete = resultColumns[2].toLowerCase().startsWith("t"); rval.groupId = Integer.parseInt(resultColumns[3]); rval.aclMemberId = resultColumns[4] == null ? null : Integer.parseInt(resultColumns[4]); rval.aclGroupId = resultColumns[5] == null ? null : Integer.parseInt(resultColumns[5]); rval.aclMemberEmail = resultColumns[6]; rval.secretId = Integer.parseInt(resultColumns[7]); rval.encryptedClientData = resultColumns[8]; rval.aclGroupName = resultColumns[9]; rval.isViewable = resultColumns[10].toLowerCase().startsWith("t"); rval.kingName = resultColumns[11]; rval.isTopLevel = resultColumns[12].toLowerCase().startsWith("t"); return rval; } })); // assume there are no nested groups // TODO: solve this properly later. // NB: These records are in no particular order, so it must build the secret data // structure incrementally, storing partial state SetMultimap<Integer, String> secretToUserSet = TreeMultimap.create(); for (GetSecretsResultType result : results) { if (secretIdsToExclude != null && secretIdsToExclude.contains(result.secretId)) { continue; } rval.add(result.secretId); SecretToPath thisSecret = secretToPath.get(result.secretId); if (null == thisSecret) { // if we force access via toplevel groups, only add secret ids for toplevel groups. // the ordering of the secrets will ensure we get the full access paths, etc. if (topLevel.equals(AdminAccess.FORCE_ACCESS_VIA_TOPLEVEL_GROUPS) && !result.isTopLevel) { // ignoring personal secret continue; } thisSecret = new SecretToPath(); secretToPath.put(result.secretId, thisSecret); thisSecret.secretId = result.secretId; // TODO: Get icons and titles in a way that doesn't destroy privacy // thisSecret.icons = Manager.getOldJsonData().getIcons(thisSecret.hostname); // thisSecret.title = Manager.getOldJsonData().getTitle(thisSecret.hostname); thisSecret.king = result.kingName; thisSecret.isViewable = result.isViewable; thisSecret.owningOrgId = null; } if (null != result.aclGroupId) { // this ACL has a nested group. // examine this to find the owning organization // NB: this owning org MAY NOT be visible above. assert (thisSecret.owningOrgId == null || thisSecret.owningOrgId.equals(result.aclGroupId)) : "Secret in more than one org! " + thisSecret.owningOrgId + " != " + result.aclGroupId; thisSecret.owningOrgId = result.aclGroupId; thisSecret.owningOrgName = result.aclGroupName; continue; } if (result.autoDelete) { secretToUserSet.put(result.secretId, result.aclMemberEmail); thisSecret.hiddenGroupsSet.add(result.groupId); } else { thisSecret.visibleGroupsSet.add(result.groupId); } if (result.aclMemberId == context.requestor.getId() && groupIds.contains(result.groupId)) { thisSecret.groupIdPath = Lists.newArrayList(result.groupId); thisSecret.encryptedClientData = result.encryptedClientData; thisSecret.encryptedCriticalData = null; thisSecret.secretId = result.secretId; } } for (SecretToPath secret : secretToPath.values()) { secret.users = Lists.newArrayList(secretToUserSet.get(secret.secretId)); secret.groups = Lists.newArrayList(secret.visibleGroupsSet); secret.hiddenGroups = Lists.newArrayList(secret.hiddenGroupsSet); } if (auditLogInfo.equals(IncludeAuditLogInfo.INCLUDE_AUDIT_LOG_INFO)) { DBServerVisibleSecret.fillRecentAuditActions(context.manager, secretToPath.values()); } return rval; }
From source file:org.onos.yangtools.yang.model.util.FilteringSchemaContextProxy.java
/** * Filters SchemaContext for yang modules * * @param delegate original SchemaContext * @param rootModules modules (yang schemas) to be available and all their dependencies (modules importing rootModule and whole chain of their imports) * @param additionalModuleIds (additional) modules (yang schemas) to be available and whole chain of their imports * *//*from w ww . ja v a 2s . co m*/ public FilteringSchemaContextProxy(final SchemaContext delegate, final Collection<ModuleId> rootModules, final Set<ModuleId> additionalModuleIds) { Preconditions.checkArgument(rootModules != null, "Base modules cannot be null."); Preconditions.checkArgument(additionalModuleIds != null, "Additional modules cannot be null."); final Builder<Module> filteredModulesBuilder = new Builder<>(); final SetMultimap<URI, Module> nsMap = Multimaps.newSetMultimap(new TreeMap<URI, Collection<Module>>(), MODULE_SET_SUPPLIER); final SetMultimap<String, Module> nameMap = Multimaps .newSetMultimap(new TreeMap<String, Collection<Module>>(), MODULE_SET_SUPPLIER); ImmutableMap.Builder<ModuleIdentifier, String> identifiersToSourcesBuilder = ImmutableMap.builder(); //preparing map to get all modules with one name but difference in revision final TreeMultimap<String, Module> nameToModulesAll = getStringModuleTreeMultimap(); nameToModulesAll.putAll(getStringModuleMap(delegate)); //in case there is a particular dependancy to view filteredModules/yang models //dependancy is checked for module name and imports processForRootModules(delegate, rootModules, filteredModulesBuilder); //adding additional modules processForAdditionalModules(delegate, additionalModuleIds, filteredModulesBuilder); filteredModulesBuilder .addAll(getImportedModules(Maps.uniqueIndex(delegate.getModules(), ModuleId.MODULE_TO_MODULE_ID), filteredModulesBuilder.build(), nameToModulesAll)); /** * Instead of doing this on each invocation of getModules(), pre-compute * it once and keep it around -- better than the set we got in. */ this.filteredModules = filteredModulesBuilder.build(); for (final Module module : filteredModules) { nameMap.put(module.getName(), module); nsMap.put(module.getNamespace(), module); identifiersToSourcesBuilder.put(module, module.getSource()); } namespaceToModules = ImmutableSetMultimap.copyOf(nsMap); nameToModules = ImmutableSetMultimap.copyOf(nameMap); identifiersToSources = identifiersToSourcesBuilder.build(); }
From source file:org.geogig.web.functional.WebAPICucumberHooks.java
/** * Checks that the repository named {@code repositoryName}, at it's commit {@code headRef}, has * the expected features as given by the {@code expectedFeatures} {@link DataTable}. * <p>/*ww w . j a va2s . c o m*/ * The {@code DataTable} top cells represent feature tree paths, and their cells beneath each * feature tree path, the feature ids expected for each layer. * <p> * A {@code question mark} indicates a wild card feature where the feature id may not be known. * <p> * Example: * * <pre> * <code> * | Points | Lines | Polygons | * | Points.1 | Lines.1 | Polygons.1 | * | Points.2 | Lines.2 | Polygons.2 | * | ? | | | *</code> * </pre> * * @param repositoryName * @param headRef * @param expectedFeatures * @throws Throwable */ @Then("^the ([^\"]*) repository's \"([^\"]*)\" in the (@[^\"]*) transaction should have the following features:$") public void verifyRepositoryContentsTx(String repositoryName, String headRef, String txId, DataTable expectedFeatures) throws Throwable { SetMultimap<String, String> expected = HashMultimap.create(); { List<Map<String, String>> asMaps = expectedFeatures.asMaps(String.class, String.class); for (Map<String, String> featureMap : asMaps) { for (Entry<String, String> entry : featureMap.entrySet()) { if (entry.getValue().length() > 0) { expected.put(entry.getKey(), context.replaceVariables(entry.getValue())); } } } } SetMultimap<String, String> actual = context.listRepo(repositoryName, headRef, txId); Map<String, Collection<String>> actualMap = actual.asMap(); Map<String, Collection<String>> expectedMap = expected.asMap(); for (String featureType : actualMap.keySet()) { assertTrue(expectedMap.containsKey(featureType)); Collection<String> actualFeatureCollection = actualMap.get(featureType); Collection<String> expectedFeatureCollection = expectedMap.get(featureType); for (String actualFeature : actualFeatureCollection) { if (expectedFeatureCollection.contains(actualFeature)) { expectedFeatureCollection.remove(actualFeature); } else if (expectedFeatureCollection.contains("?")) { expectedFeatureCollection.remove("?"); } else { fail(); } } assertEquals(0, expectedFeatureCollection.size()); expectedMap.remove(featureType); } assertEquals(0, expectedMap.size()); }
From source file:tiger.NewInjectorGenerator.java
private void generateProvisionMethodForMap(final NewBindingKey key, TypeElement referencingClass, String suffix) {/*w ww . j a v a 2s .co m*/ TypeSpec.Builder componentSpecBuilder = getInjectorTypeSpecBuilder(getInjectorFor(key, referencingClass)); // messager.printMessage(Kind.NOTE, "generateProvisionMethodForSet: " + key + // " PackagedInjector: " // + getInjectorFor(key, referencingClass) + " SpecBuilder: " + componentSpecBuilder); ParameterizedTypeName type = (ParameterizedTypeName) key.getTypeName(); Preconditions.checkArgument(type.rawType.equals(ClassName.get(Map.class))); MethodSpec.Builder methodSpecBuilder = MethodSpec.methodBuilder(getProvisionMethodName(key) + suffix) .addModifiers(suffix.isEmpty() ? Modifier.PUBLIC : Modifier.PRIVATE).returns(type); methodSpecBuilder.addStatement("$T result = new $T<>()", type, HashMap.class); methodSpecBuilder.addStatement("$T packagedMap", type); SetMultimap<PackageElement, NewDependencyInfo> packageToDependencyInfoMap = HashMultimap.create(); Set<NewDependencyInfo> dependencyInfos = Utils.getDependencyInfo(dependencies, key); Preconditions.checkNotNull(dependencyInfos, String.format("dependencyInfo not found for key: %s", key)); for (NewDependencyInfo dependencyInfo : Utils.getDependencyInfo(dependencies, key)) { packageToDependencyInfoMap.put(Utils.getPackage(dependencyInfo.getSourceClassElement()), dependencyInfo); } for (PackageElement pkg : packageToDependencyInfoMap.keySet()) { // messager.printMessage(Kind.NOTE, String.format("generateProvisionMethodForSet for %s from" // + // " %s", key, packageToDependencyInfoMap.get(pkg))); generateMapTypeProvisionMethodForPackage(key, packageToDependencyInfoMap.get(pkg), suffix); NewDependencyInfo dependencyInfo = Iterables.getFirst(packageToDependencyInfoMap.get(pkg), null); Preconditions.checkNotNull(dependencyInfo, String.format("no dependencyInfo for set key %s in module %s", key, pkg)); ClassName packagedInjectorClassName = getPackagedInjectorForNewDependencyInfo(key, dependencyInfo); methodSpecBuilder.addStatement("packagedMap = $L.$N().$N()", TOP_LEVEL_INJECTOR_FIELD, Utils.getGetMethodName(packagedInjectorClassName), getProvisionMethodName(key)); methodSpecBuilder.addStatement("result.putAll($L)", "packagedMap"); } methodSpecBuilder.addStatement("return result"); componentSpecBuilder.addMethod(methodSpecBuilder.build()); }
From source file:com.android.sdklib.repository.local.LocalAddonPkgInfo.java
/** * Get all the system images supported by an add-on target. * For an add-on, we first look in the new sdk/system-images folders then we look * for sub-folders in the addon/images directory. * If none are found but the directory exists and is not empty, assume it's a legacy * arm eabi system image./*ww w . j a v a2 s.c o m*/ * If any given API appears twice or more, the first occurrence wins. * <p/> * Note that it's OK for an add-on to have no system-images at all, since it can always * rely on the ones from its base platform. * * @param fileOp File operation wrapper. * @return an array of ISystemImage containing all the system images for the target. * The list can be empty but not null. */ @NonNull private ISystemImage[] getAddonSystemImages(IFileOp fileOp) { Set<ISystemImage> found = new TreeSet<ISystemImage>(); SetMultimap<IdDisplay, String> tagToAbiFound = TreeMultimap.create(); // Look in the system images folders: // - SDK/system-image/platform/addon-id-tag/abi // - SDK/system-image/addon-id-tag/abi (many abi possible) // Optional: look for skins under // - SDK/system-image/platform/addon-id-tag/abi/skins/skin-name // - SDK/system-image/addon-id-tag/abi/skins/skin-name // If we find multiple occurrences of the same platform/abi, the first one read wins. LocalPkgInfo[] sysImgInfos = getLocalSdk().getPkgsInfos(PkgType.PKG_ADDON_SYS_IMAGE); for (LocalPkgInfo pkg : sysImgInfos) { IPkgDesc d = pkg.getDesc(); if (pkg instanceof LocalAddonSysImgPkgInfo && d.hasVendor() && mAddonDesc.getVendor().equals(d.getVendor()) && mAddonDesc.getName().equals(d.getTag()) && Objects.equal(mAddonDesc.getAndroidVersion(), pkg.getDesc().getAndroidVersion())) { final IdDisplay tag = mAddonDesc.getName(); final String abi = d.getPath(); if (abi != null && !tagToAbiFound.containsEntry(tag, abi)) { found.add(((LocalAddonSysImgPkgInfo) pkg).getSystemImage()); tagToAbiFound.put(tag, abi); } } } // Look for sub-directories: // - SDK/addons/addon-name/images/abi (multiple abi possible) // - SDK/addons/addon-name/armeabi (legacy support) boolean useLegacy = true; boolean hasImgFiles = false; final IdDisplay defaultTag = SystemImage.DEFAULT_TAG; File imagesDir = new File(getLocalDir(), SdkConstants.OS_IMAGES_FOLDER); File[] files = fileOp.listFiles(imagesDir); for (File file : files) { if (fileOp.isDirectory(file)) { useLegacy = false; String abi = file.getName(); if (!tagToAbiFound.containsEntry(defaultTag, abi)) { found.add(new SystemImage(file, LocationType.IN_IMAGES_SUBFOLDER, SystemImage.DEFAULT_TAG, mAddonDesc.getVendor(), abi, FileOp.EMPTY_FILE_ARRAY)); tagToAbiFound.put(defaultTag, abi); } } else if (!hasImgFiles && fileOp.isFile(file)) { if (file.getName().endsWith(".img")) { //$NON-NLS-1$ // The legacy images folder is only valid if it contains some .img files hasImgFiles = true; } } } if (useLegacy && hasImgFiles && fileOp.isDirectory(imagesDir) && !tagToAbiFound.containsEntry(defaultTag, SdkConstants.ABI_ARMEABI)) { // We found no sub-folder system images but it looks like the top directory // has some img files in it. It must be a legacy ARM EABI system image folder. found.add(new SystemImage(imagesDir, LocationType.IN_LEGACY_FOLDER, SystemImage.DEFAULT_TAG, SdkConstants.ABI_ARMEABI, FileOp.EMPTY_FILE_ARRAY)); } return found.toArray(new ISystemImage[found.size()]); }
From source file:ome.services.graphs.GraphTraversal.java
/** * Traverse model object graph to determine steps for the proposed operation. * @param session the Hibernate session to use for HQL queries * @param objects the model objects to process * @param include if the given model objects are to be included (instead of just deleted) * @param applyRules if the given model objects should have the policy rules applied to them * @return the model objects included in the operation, and the deleted objects * @throws GraphException if the model objects were not as expected *///from w ww . j a v a 2 s . c om public Entry<SetMultimap<String, Long>, SetMultimap<String, Long>> planOperation(Session session, SetMultimap<String, Long> objects, boolean include, boolean applyRules) throws GraphException { if (progress.contains(Milestone.PLANNED)) { throw new IllegalStateException("operation already planned"); } final Set<CI> targetSet = include ? planning.included : planning.deleted; /* note the object instances for processing */ targetSet.addAll(objectsToCIs(session, objects)); if (applyRules) { /* actually do the planning of the operation */ planning.toProcess.addAll(targetSet); planOperation(session); } else { /* act as if the target objects have no links and no rules match them */ for (final CI targetObject : targetSet) { planning.blockedBy.put(targetObject, new HashSet<CI>()); } } progress.add(Milestone.PLANNED); /* report which objects are to be included in the operation or deleted so that it can proceed */ final SetMultimap<String, Long> included = HashMultimap.create(); for (final CI includedObject : planning.included) { included.put(includedObject.className, includedObject.id); } final SetMultimap<String, Long> deleted = HashMultimap.create(); for (final CI deletedObject : planning.deleted) { deleted.put(deletedObject.className, deletedObject.id); } return Maps.immutableEntry(included, deleted); }
From source file:omero.cmd.graphs.Chmod2I.java
@Override public Object step(int step) throws Cancel { helper.assertStep(step);//from www.ja va 2s . co m try { switch (step) { case 0: /* if targetObjects were an IObjectList then this would need IceMapper.reverse */ final SetMultimap<String, Long> targetMultimap = HashMultimap.create(); for (final Entry<String, List<Long>> oneClassToTarget : targetObjects.entrySet()) { /* determine actual class from given target object class name */ String targetObjectClassName = oneClassToTarget.getKey(); final int lastDot = targetObjectClassName.lastIndexOf('.'); if (lastDot > 0) { targetObjectClassName = targetObjectClassName.substring(lastDot + 1); } final Class<? extends IObject> targetObjectClass = graphPathBean .getClassForSimpleName(targetObjectClassName); /* check that it is legal to target the given class */ final Iterator<Class<? extends IObject>> legalTargetsIterator = targetClasses.iterator(); do { if (!legalTargetsIterator.hasNext()) { final Exception e = new IllegalArgumentException( "cannot target " + targetObjectClassName); throw helper.cancel(new ERR(), e, "bad-target"); } } while (!legalTargetsIterator.next().isAssignableFrom(targetObjectClass)); /* note IDs to target for the class */ final Collection<Long> ids = oneClassToTarget.getValue(); targetMultimap.putAll(targetObjectClass.getName(), ids); targetObjectCount += ids.size(); } /* only downgrade to private requires the graph policy rules to be applied */ final Entry<SetMultimap<String, Long>, SetMultimap<String, Long>> plan; final Permissions newPermissions = Utils.toPermissions(perm1); final boolean isToGroupReadable = newPermissions.isGranted(Permissions.Role.GROUP, Permissions.Right.READ); if (isToGroupReadable) { /* can always skip graph policy rules as is not downgrade to private */ plan = graphTraversal.planOperation(helper.getSession(), targetMultimap, true, false); } else { /* determine which target groups are not already private ... */ final String groupClass = ExperimenterGroup.class.getName(); final SetMultimap<String, Long> targetsNotPrivate = HashMultimap.create(); final Map<Long, Boolean> readableByGroupId = new HashMap<Long, Boolean>(); for (final Long groupId : targetMultimap.get(groupClass)) { Boolean isFromGroupReadable = readableByGroupId.get(groupId); if (isFromGroupReadable == null) { final Session session = helper.getSession(); final ExperimenterGroup group = (ExperimenterGroup) session.get(ExperimenterGroup.class, groupId); if (group == null) { final Exception e = new IllegalArgumentException("no group " + groupId); throw helper.cancel(new ERR(), e, "bad-group"); } final Permissions permissions = group.getDetails().getPermissions(); isFromGroupReadable = permissions.isGranted(Permissions.Role.GROUP, Permissions.Right.READ); readableByGroupId.put(groupId, isFromGroupReadable); } if (isFromGroupReadable) { targetsNotPrivate.put(groupClass, groupId); } } /* ... and apply the graph policy rules to those */ plan = graphTraversal.planOperation(helper.getSession(), targetsNotPrivate, true, true); } return Maps.immutableEntry(plan.getKey(), GraphUtil.arrangeDeletionTargets(helper.getSession(), plan.getValue())); case 1: graphTraversal.assertNoPolicyViolations(); return null; case 2: processor = graphTraversal.processTargets(); return null; case 3: unlinker = graphTraversal.unlinkTargets(false); graphTraversal = null; return null; case 4: unlinker.execute(); return null; case 5: processor.execute(); return null; default: final Exception e = new IllegalArgumentException( "model object graph operation has no step " + step); throw helper.cancel(new ERR(), e, "bad-step"); } } catch (Cancel c) { throw c; } catch (GraphException ge) { final omero.cmd.GraphException graphERR = new omero.cmd.GraphException(); graphERR.message = ge.message; throw helper.cancel(graphERR, ge, "graph-fail"); } catch (Throwable t) { throw helper.cancel(new ERR(), t, "graph-fail"); } }