List of usage examples for com.google.common.collect BiMap isEmpty
boolean isEmpty();
From source file:net.derquinse.common.collect.ImmutableIndexedHierarchy.java
/** * Returns an immutable indexed hierarchy backed by a bimap and a hierarchy. * @param map Backing map.//from w w w . j av a2s. co m * @param hierarchy Backing hierachy. */ public static <K, V> ImmutableIndexedHierarchy<K, V> of(BiMap<? extends K, ? extends V> map, Hierarchy<? extends K> hierarchy) { check(map, hierarchy); if (map.isEmpty()) { return of(); } return new RegularImmutableIndexedHierarchy<K, V>(ImmutableBiMap.copyOf(map), ImmutableHierarchy.copyOf(hierarchy)); }
From source file:cuchaz.enigma.convert.MappingsConverter.java
public static void convertMappings(Mappings mappings, BiMap<ClassEntry, ClassEntry> changes) { // sort the changes so classes are renamed in the correct order // ie. if we have the mappings a->b, b->c, we have to apply b->c before a->b LinkedHashMap<ClassEntry, ClassEntry> sortedChanges = Maps.newLinkedHashMap(); int numChangesLeft = changes.size(); while (!changes.isEmpty()) { Iterator<Map.Entry<ClassEntry, ClassEntry>> iter = changes.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<ClassEntry, ClassEntry> change = iter.next(); if (changes.containsKey(change.getValue())) { sortedChanges.put(change.getKey(), change.getValue()); iter.remove();/*from ww w .j ava2 s . c o m*/ } } // did we remove any changes? if (numChangesLeft - changes.size() > 0) { // keep going numChangesLeft = changes.size(); } else { // can't sort anymore. There must be a loop break; } } if (!changes.isEmpty()) { throw new Error("Unable to sort class changes! There must be a cycle."); } // convert the mappings in the correct class order for (Map.Entry<ClassEntry, ClassEntry> entry : sortedChanges.entrySet()) { mappings.renameObfClass(entry.getKey().getName(), entry.getValue().getName()); } }
From source file:org.apache.usergrid.tools.RemoveAdminUserFromOrg.java
@Override public void runTool(CommandLine line) throws Exception { startSpring();//from w ww .jav a 2s .c o m String orgName = line.getOptionValue("org"); String email = line.getOptionValue("user"); if (orgName == null) { System.out.println("org argument is required"); } if (email == null) { System.out.println("user argument is required"); } boolean remove = line.hasOption("remove"); // get user and org objects UUID ownerId = emf.getManagementAppId(); CpEntityManager em = (CpEntityManager) emf.getEntityManager(ownerId); UserInfo userInfo = managementService.getAdminUserByEmail(email); User user = em.get(userInfo.getUuid(), User.class); OrganizationInfo orgInfo = managementService.getOrganizationByName(orgName); Group group = em.get(orgInfo.getUuid(), Group.class); StringBuilder sb = new StringBuilder(); try { sb.append("\nUser ").append(user.getUsername()).append(":").append(user.getUuid().toString()); sb.append("\nOrganization ").append(orgName).append(":").append(orgInfo.getUuid()); //--------------------------------------------------------------------------------------------- // log connections found via entity manager and management service Results users = em.getCollection(group, "users", null, 1000, Query.Level.ALL_PROPERTIES, false); if (users.isEmpty()) { sb.append("\n Organization has no Users\n"); } else { sb.append("\n Organization has Users:\n"); for (Entity entity : users.getEntities()) { sb.append(" User ").append(entity.getUuid()).append(":").append(entity.getName()); sb.append("\n"); } } BiMap<UUID, String> orgsForAdminUser = managementService.getOrganizationsForAdminUser(user.getUuid()); if (orgsForAdminUser.isEmpty()) { sb.append(" User has no Organizations\n"); } else { sb.append(" User has Organizations\n"); for (UUID key : orgsForAdminUser.keySet()) { String name = orgsForAdminUser.get(key); sb.append(" Organization ").append(name).append(":").append(key).append("\n"); } } List<UserInfo> adminUsers = managementService.getAdminUsersForOrganization(orgInfo.getUuid()); if (adminUsers.isEmpty()) { sb.append(" Organization has no Admin Users\n"); } else { sb.append(" Organization has Admin Users:").append("\n"); for (UserInfo info : adminUsers) { sb.append(" Admin User ").append(info.getUsername()).append(":").append(info.getUuid()) .append("\n"); } } //--------------------------------------------------------------------------------------------- // log connections found via graph manager final GraphManagerFactory gmf = injector.getInstance(GraphManagerFactory.class); final GraphManager graphManager = gmf.createEdgeManager( new ApplicationScopeImpl(new SimpleId(emf.getManagementAppId(), Application.ENTITY_TYPE))); final Id groupId = new SimpleId(orgInfo.getUuid(), Group.ENTITY_TYPE); final Id userId = new SimpleId(user.getUuid(), User.ENTITY_TYPE); // edge versions from group -> user sb.append("Edges from collectionToEntity:\n"); SearchByEdge collectionToEntity = CpNamingUtils.createEdgeFromCollectionName(groupId, "users", userId); graphManager.loadEdgeVersions(collectionToEntity).forEach(edge -> sb.append("edge from ") .append(edge.getSourceNode()).append(" to ").append(edge.getTargetNode())); sb.append("\n"); // edge versions from user -> group sb.append("Edges from entityToCollection:\n"); SearchByEdge entityToCollection = CpNamingUtils.createEdgeFromCollectionName(userId, "groups", groupId); graphManager.loadEdgeVersions(entityToCollection).forEach(edge -> sb.append("edge from ") .append(edge.getSourceNode()).append(" to ").append(edge.getTargetNode()).append("\n")); //--------------------------------------------------------------------------------------------- // optionally remove admin user if (remove) { // use normal means to remove user from org managementService.removeAdminUserFromOrganization(user.getUuid(), orgInfo.getUuid()); } // make sure no edges left behind String usersCollType = CpNamingUtils.getEdgeTypeFromCollectionName("users"); sb.append("Edges of type ").append(usersCollType).append(" targeting user:\n"); graphManager.loadEdgesToTarget(createSearch(userId, usersCollType)).forEach(edge -> { if (remove && edge.getSourceNode().getUuid().equals(group.getUuid())) { sb.append(" DELETING edge from ").append(edge.getSourceNode()).append(" to ") .append(edge.getTargetNode()).append("\n"); graphManager.markEdge(edge); graphManager.deleteEdge(edge); } else { sb.append(" edge from ").append(edge.getSourceNode()).append(" to ") .append(edge.getTargetNode()).append("\n"); } }); sb.append("Edges of type ").append(usersCollType).append(" sourced from group:\n"); graphManager.loadEdgesFromSource(createSearch(groupId, usersCollType)).forEach(edge -> { if (remove && edge.getTargetNode().getUuid().equals(user.getUuid())) { sb.append(" DELETING edge from ").append(edge.getSourceNode()).append(" to ") .append(edge.getTargetNode()).append("\n"); graphManager.markEdge(edge).toBlocking().lastOrDefault(null); graphManager.deleteEdge(edge).toBlocking().lastOrDefault(null); } else { sb.append(" edge from ").append(edge.getSourceNode()).append(" to ") .append(edge.getTargetNode()).append("\n"); } }); } finally { logger.info(sb.toString()); } }
From source file:org.eclipse.sirius.common.tools.api.editing.FileStatusPrecommitListener.java
/** * {@inheritDoc}//from w w w .j a va 2 s . c o m */ @Override public Command transactionAboutToCommit(final ResourceSetChangeEvent event) throws RollbackException { final boolean defensiveEditValidation = Platform.getPreferencesService().getBoolean( "org.eclipse.sirius.common.ui", CommonPreferencesConstants.PREF_DEFENSIVE_EDIT_VALIDATION, true, //$NON-NLS-1$ null); final Command cmd = super.transactionAboutToCommit(event); if (defensiveEditValidation) { final Set<Resource> changedRes = Sets.newLinkedHashSet(); if (!event.getTransaction().isReadOnly()) { for (org.eclipse.emf.common.notify.Notification notif : Iterables.filter(event.getNotifications(), org.eclipse.emf.common.notify.Notification.class)) { if (notif.getNotifier() instanceof EObject) { final Resource res = ((EObject) notif.getNotifier()).eResource(); if (resourceChange(res, notif)) { changedRes.add(res); } } } } final BiMap<IFile, Resource> files2Validate = HashBiMap.create(); final Iterator<Resource> it = changedRes.iterator(); while (it.hasNext()) { final Resource nextResource = it.next(); final IFile file = WorkspaceSynchronizer.getFile(nextResource); if (file != null && file.isReadOnly()) { files2Validate.put(file, nextResource); } } if (!files2Validate.isEmpty()) { final RollbackException cancelException = new RollbackException( new Status(IStatus.CANCEL, DslCommonPlugin.PLUGIN_ID, Messages.FileStatusPrecommitListener_fileModificationValidationStatus)); final MultiStatus status = new MultiStatus(DslCommonPlugin.PLUGIN_ID, IStatus.ERROR, Messages.FileStatusPrecommitListener_fileModificationValidationStatus, cancelException); if (fileModificationValidators.isEmpty()) { // No extension found, use the default process. status.add(ResourcesPlugin.getWorkspace().validateEdit( files2Validate.keySet().toArray(new IFile[files2Validate.size()]), IWorkspace.VALIDATE_PROMPT)); } else { for (final IFileModificationValidator fileModificationValidator : fileModificationValidators) { final IStatus validationStatus = fileModificationValidator .validateEdit(files2Validate.keySet()); if (validationStatus != null) { status.add(validationStatus); } } } if (!status.isOK()) { throw cancelException; } } } return cmd; }
From source file:org.cloudsmith.geppetto.pp.dsl.ui.container.PPWorkspaceProjectsStateHelper.java
/** * Returns the best matching project (or null if there is no match) among the projects in the * workspace.//from w w w . j a va 2 s .com * A translation is made from "/" to "-" in the separators in dependencies. (Should be checked elsewhere). * * @param d * @return */ protected IProject getBestMatchingProject(Dependency d) { ModuleName name = d.getName(); if (name == null) return null; // Names with "/" are not allowed name = name.withSeparator('-'); String namepart = name + "-"; BiMap<IProject, Version> candidates = HashBiMap.create(); int len = namepart.length(); for (IProject p : getWorkspaceRoot().getProjects()) { String n = p.getName(); if (n.startsWith(namepart) && n.length() > len && isAccessibleXtextProject(p)) { try { candidates.put(p, Version.create(p.getName().substring(len))); } catch (IllegalArgumentException e) { // Project name does not end with a valid version. Just skip it } } } if (candidates.isEmpty()) return null; VersionRange vr = d.getVersionRequirement(); if (vr == null) vr = VersionRange.ALL_INCLUSIVE; Version best = vr.findBestMatch(candidates.values()); return candidates.inverse().get(best); }
From source file:com.puppetlabs.geppetto.pp.dsl.ui.container.PPWorkspaceProjectsStateHelper.java
/** * Returns the best matching project (or null if there is no match) among the projects in the * workspace./*from ww w . ja v a 2s .c om*/ * A translation is made from "/" to "-" in the separators in dependencies. (Should be checked elsewhere). * * @param d * @return */ protected IProject getBestMatchingProject(Dependency d) { ModuleName name = d.getName(); if (name == null) return null; String namepart = name + "-"; BiMap<IProject, Version> candidates = HashBiMap.create(); int len = namepart.length(); for (IProject p : getWorkspaceRoot().getProjects()) { String n = p.getName(); if (n.startsWith(namepart) && n.length() > len && isAccessibleXtextProject(p)) { try { candidates.put(p, Version.fromString(p.getName().substring(len))); } catch (IllegalArgumentException e) { // Project name does not end with a valid version. Just skip it } } } if (candidates.isEmpty()) return null; VersionRange vr = d.getVersionRequirement(); if (vr == null) vr = VersionRange.ALL_INCLUSIVE; Version best = vr.findBestMatch(candidates.values()); return candidates.inverse().get(best); }
From source file:org.cloudsmith.geppetto.pp.dsl.ui.builder.PPModuleMetadataBuilder.java
private static IProject getBestMatchingProject(ModuleName name, VersionRange vr, ITracer tracer, IProgressMonitor monitor) {/*ww w . jav a 2 s.c o m*/ // Names with "/" are not allowed if (name == null) { if (tracer.isTracing()) tracer.trace("Dependency with missing name found"); return null; } name = name.withSeparator('-'); if (tracer.isTracing()) tracer.trace("Resolving required name: ", name); BiMap<IProject, Version> candidates = HashBiMap.create(); if (tracer.isTracing()) tracer.trace("Checking against all projects..."); for (IProject p : getWorkspaceRoot().getProjects()) { if (!isAccessiblePuppetProject(p)) { if (tracer.isTracing()) tracer.trace("Project not accessible: ", p.getName()); continue; } Version version = null; ModuleName moduleName = null; try { String mn = p.getPersistentProperty(PROJECT_PROPERTY_MODULENAME); moduleName = mn == null ? null : new ModuleName(mn); } catch (CoreException e) { log.error("Could not read project Modulename property", e); } if (tracer.isTracing()) tracer.trace("Project: ", p.getName(), " has persisted name: ", moduleName); boolean matched = false; if (name.equals(moduleName)) matched = true; if (tracer.isTracing()) { if (!matched) tracer.trace("== not matched on name"); } // get the version from the persisted property if (matched) { try { version = Version.create(p.getPersistentProperty(PROJECT_PROPERTY_MODULEVERSION)); } catch (Exception e) { log.error("Error while getting version from project", e); } if (version == null) version = Version.MIN; if (tracer.isTracing()) tracer.trace("Candidate with version; ", version.toString(), " added as candidate"); candidates.put(p, version); } } if (candidates.isEmpty()) { if (tracer.isTracing()) tracer.trace("No candidates found"); return null; } if (tracer.isTracing()) { tracer.trace("Getting best version"); } // find best version and do a lookup of project if (vr == null) vr = VersionRange.ALL_INCLUSIVE; Version best = vr.findBestMatch(candidates.values()); if (best == null) { if (tracer.isTracing()) tracer.trace("No best match found"); return null; } if (tracer.isTracing()) { tracer.trace("Found best project: ", candidates.inverse().get(best).getName(), "having version:", best); } return candidates.inverse().get(best); }
From source file:com.puppetlabs.geppetto.pp.dsl.ui.builder.PPModuleMetadataBuilder.java
private static IProject getBestMatchingProject(ModuleName name, VersionRange vr, ITracer tracer) { // Names with "/" are not allowed if (name == null) { if (tracer.isTracing()) tracer.trace("Dependency with missing name found"); return null; }/* w w w .jav a 2 s . co m*/ if (tracer.isTracing()) tracer.trace("Resolving required name: ", name); BiMap<IProject, Version> candidates = HashBiMap.create(); if (tracer.isTracing()) tracer.trace("Checking against all projects..."); for (IProject p : getWorkspaceRoot().getProjects()) { if (!isAccessiblePuppetProject(p)) { if (tracer.isTracing()) tracer.trace("Project not accessible: ", p.getName()); continue; } Version version = null; ModuleName moduleName = null; try { String mn = p.getPersistentProperty(PROJECT_PROPERTY_MODULENAME); moduleName = mn == null ? null : ModuleName.fromString(mn); } catch (CoreException e) { log.error("Could not read project Modulename property", e); } if (tracer.isTracing()) tracer.trace("Project: ", p.getName(), " has persisted name: ", moduleName); boolean matched = false; if (name.equals(moduleName)) matched = true; if (tracer.isTracing()) { if (!matched) tracer.trace("== not matched on name"); } // get the version from the persisted property if (matched) { try { version = Version.fromString(p.getPersistentProperty(PROJECT_PROPERTY_MODULEVERSION)); } catch (Exception e) { log.error("Error while getting version from project", e); } if (version == null) version = Version.MIN; if (tracer.isTracing()) tracer.trace("Candidate with version; ", version.toString(), " added as candidate"); candidates.put(p, version); } } if (candidates.isEmpty()) { if (tracer.isTracing()) tracer.trace("No candidates found"); return null; } if (tracer.isTracing()) { tracer.trace("Getting best version"); } // find best version and do a lookup of project if (vr == null) vr = VersionRange.ALL_INCLUSIVE; Version best = vr.findBestMatch(candidates.values()); if (best == null) { if (tracer.isTracing()) tracer.trace("No best match found"); return null; } if (tracer.isTracing()) { tracer.trace("Found best project: ", candidates.inverse().get(best).getName(), "having version:", best); } return candidates.inverse().get(best); }
From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java
/** * Fills the missing genotype values for the new loaded samples. * Missing data is which was present in the database but not in the input file. * Data present in the file but not in the database is added during the {@link #insert} step. * * +--------+---------+/*from w w w . j av a 2 s . co m*/ * | Loaded | NewFile | * +--------+--------+---------+ * | 10:A:T | DATA | | <- Missing data to be filled * +--------+--------+---------+ * | 20:C:T | | DATA | <- Missing data already filled in the {@link #insert} step. * +--------+--------+---------+ * * * * @param fileId Loading File ID * @param chromosomes Chromosomes covered by the current file * @param fileSampleIds FileSampleIds * @param studyConfiguration StudyConfiguration * @return WriteResult */ QueryResult<UpdateResult> fillFileGaps(int fileId, List<String> chromosomes, List<Integer> fileSampleIds, StudyConfiguration studyConfiguration) { // { "studies.sid" : <studyId>, "studies.files.fid" : { $ne : <fileId> } }, // { $push : { // "studies.$.gt.?/?" : {$each : [ <fileSampleIds> ] } // } } if (studyConfiguration.getAttributes().getAsStringList(DEFAULT_GENOTYPE.key(), "") .equals(Collections.singletonList(DocumentToSamplesConverter.UNKNOWN_GENOTYPE)) // && studyConfiguration.getAttributes().getAsStringList(VariantStorageManager.Options.EXTRA_GENOTYPE_FIELDS.key()).isEmpty() ) { // Check if the default genotype is the unknown genotype. In that case, is not required to fill missing genotypes. // Previously, also checks if there where EXTRA_GENOTYPE_FIELDS like DP:AD,... . In that case, those arrays had to be filled. logger.debug("Do not need fill gaps. DefaultGenotype is UNKNOWN_GENOTYPE({}).", DocumentToSamplesConverter.UNKNOWN_GENOTYPE); return new QueryResult<>(); } else if (studyConfiguration.getAttributes().getBoolean( VariantStorageManager.Options.EXCLUDE_GENOTYPES.key(), VariantStorageManager.Options.EXCLUDE_GENOTYPES.defaultValue())) { // Check if the genotypes are not required. In that case, no fillGaps is needed logger.debug("Do not need fill gaps. Exclude genotypes."); return new QueryResult<>(); } else { BiMap<String, Integer> indexedSamples = StudyConfiguration.getIndexedSamples(studyConfiguration); if (indexedSamples.isEmpty() || indexedSamples.values().equals(new HashSet<>(fileSampleIds))) { // If the loaded samples match with the current samples means that there where no other samples loaded. // There were no gaps, so it is not needed to fill anything. logger.debug("Do not need fill gaps. First sample batch."); return new QueryResult<>(); } } logger.debug("Do fill gaps."); Document query = new Document(); if (chromosomes != null && !chromosomes.isEmpty()) { query.put(DocumentToVariantConverter.CHROMOSOME_FIELD, new Document("$in", chromosomes)); } query.put(DocumentToVariantConverter.STUDIES_FIELD, new Document("$elemMatch", new Document(DocumentToStudyVariantEntryConverter.STUDYID_FIELD, studyConfiguration.getStudyId()) .append(DocumentToStudyVariantEntryConverter.FILES_FIELD + "." + DocumentToStudyVariantEntryConverter.FILEID_FIELD, new Document("$ne", fileId)))); Document push = new Document().append(DocumentToVariantConverter.STUDIES_FIELD + ".$." + DocumentToStudyVariantEntryConverter.GENOTYPES_FIELD + "." + DocumentToSamplesConverter.UNKNOWN_GENOTYPE, new Document("$each", fileSampleIds)); // List<Integer> loadedSamples = getLoadedSamples(fileId, studyConfiguration); // List<Object> missingOtherValues = new ArrayList<>(fileSampleIds.size()); // for (int size = fileSampleIds.size(); size > 0; size--) { // missingOtherValues.add(DBObjectToSamplesConverter.UNKNOWN_FIELD); // } // List<String> extraFields = studyConfiguration.getAttributes() // .getAsStringList(VariantStorageManager.Options.EXTRA_GENOTYPE_FIELDS.key()); // for (String extraField : extraFields) { // push.put(DBObjectToVariantConverter.STUDIES_FIELD + ".$." + extraField.toLowerCase(), // new Document("$each", missingOtherValues).append("$position", loadedSamples.size()) // ); // } Document update = new Document("$push", push); QueryOptions queryOptions = new QueryOptions(MULTI, true); logger.debug("FillGaps find : {}", query); logger.debug("FillGaps update : {}", update); return variantsCollection.update(query, update, queryOptions); }
From source file:com.cloudera.director.aws.ec2.EC2Provider.java
/** * Returns a map from virtual instance IDs to instance state for the specified batch of virtual * instance IDs.//from w w w.j a va2s . co m * * @param virtualInstanceIds batch of virtual instance IDs * @return the map from instance IDs to instance state for the specified batch of virtual * instance IDs */ private Map<String, InstanceState> getBatchInstanceState(Collection<String> virtualInstanceIds) { Map<String, InstanceState> instanceStateByVirtualInstanceId = Maps .newHashMapWithExpectedSize(virtualInstanceIds.size()); BiMap<String, String> virtualInstanceIdsByEC2InstanceId = getEC2InstanceIdsByVirtualInstanceId( virtualInstanceIds).inverse(); int page = 0; LOG.info(">> Fetching page {}", page); if (virtualInstanceIdsByEC2InstanceId.isEmpty()) { // No EC2 instances are found, which means these id's are already terminated and gone. // In practice, this is possible when no instances were provisioned to begin with. // For example, when a deployment fails due to tagging error. return instanceStateByVirtualInstanceId; } DescribeInstanceStatusResult result = client.describeInstanceStatus(new DescribeInstanceStatusRequest() // Note that sending in an empty set will result in fetching _all_ instance Ids. // It requires you to send one or more EC2 Ids .withInstanceIds(virtualInstanceIdsByEC2InstanceId.keySet()).withIncludeAllInstances(true)); LOG.info("<< Result: {}", result); while (!result.getInstanceStatuses().isEmpty()) { for (InstanceStatus status : result.getInstanceStatuses()) { InstanceStateName currentState = InstanceStateName.fromValue(status.getInstanceState().getName()); String ec2InstanceId = status.getInstanceId(); String virtualInstanceId = virtualInstanceIdsByEC2InstanceId.get(ec2InstanceId); InstanceState instanceState = EC2InstanceState.fromInstanceStateName(currentState); instanceStateByVirtualInstanceId.put(virtualInstanceId, instanceState); } String nextToken = result.getNextToken(); if (nextToken != null) { page++; LOG.info(">> Fetching page {} using token {}", page, nextToken); result = client .describeInstanceStatus(new DescribeInstanceStatusRequest().withNextToken(nextToken)); LOG.info("<< Result: {}", result); } else { break; } } return instanceStateByVirtualInstanceId; }