List of usage examples for java.util Collection remove
boolean remove(Object o);
From source file:com.facebook.model.GraphObjectFactoryTests.java
@SmallTest @MediumTest//from www .j a v a 2 s . com @LargeTest public void testCollectionRemoveThrows() throws JSONException { try { Collection<Integer> collection = GraphObject.Factory.createList(Integer.class); collection.remove(5); fail("Expected exception"); } catch (UnsupportedOperationException exception) { } }
From source file:com.datatorrent.contrib.kinesis.AbstractKinesisInputOperator.java
private void removePartitionsForClosedShards(Collection<Partition<AbstractKinesisInputOperator>> partitions, Set<Integer> deletedOperators) { List<Partition<AbstractKinesisInputOperator>> closedPartitions = new ArrayList<Partition<AbstractKinesisInputOperator>>(); for (Partition<AbstractKinesisInputOperator> op : partitions) { if (op.getPartitionedInstance().getConsumer().getClosedShards().size() == op.getPartitionedInstance() .getConsumer().getNumOfShards()) { closedPartitions.add(op);/*from ww w . jav a 2 s . c om*/ deletedOperators.add(op.getPartitionedInstance().operatorId); } } if (closedPartitions.size() != 0) { for (Partition<AbstractKinesisInputOperator> op : closedPartitions) { partitions.remove(op); } } }
From source file:admin.service.SimpleJobService.java
@Override public Collection<StepExecution> getStepExecutions(Long jobExecutionId) throws NoSuchJobExecutionException { JobExecution jobExecution = jobExecutionDao.getJobExecution(jobExecutionId); if (jobExecution == null) { throw new NoSuchJobExecutionException("No JobExecution with id=" + jobExecutionId); }/*w w w . java 2 s. c om*/ stepExecutionDao.addStepExecutions(jobExecution); String jobName = jobExecution.getJobInstance() == null ? jobInstanceDao.getJobInstance(jobExecution).getJobName() : jobExecution.getJobInstance().getJobName(); Collection<String> missingStepNames = new LinkedHashSet<String>(); if (jobName != null) { missingStepNames.addAll(stepExecutionDao.findStepNamesForJobExecution(jobName, "*:partition*")); logger.debug("Found step executions in repository: " + missingStepNames); } Job job = null; try { job = jobLocator.getJob(jobName); } catch (NoSuchJobException e) { // expected } if (job instanceof StepLocator) { Collection<String> stepNames = ((StepLocator) job).getStepNames(); missingStepNames.addAll(stepNames); logger.debug("Added step executions from job: " + missingStepNames); } for (StepExecution stepExecution : jobExecution.getStepExecutions()) { String stepName = stepExecution.getStepName(); if (missingStepNames.contains(stepName)) { missingStepNames.remove(stepName); } logger.debug("Removed step executions from job execution: " + missingStepNames); } for (String stepName : missingStepNames) { StepExecution stepExecution = jobExecution.createStepExecution(stepName); stepExecution.setStatus(BatchStatus.UNKNOWN); } return jobExecution.getStepExecutions(); }
From source file:it.cnr.icar.eric.client.ui.thin.jsf.ClassSchemeGraphBean.java
private Collection<ClassificationScheme> filterHiddenSchemes(Collection<ClassificationScheme> classSchemes) throws JAXRException { Collection<ClassificationScheme> filteredSchemes = null; String hiddenSchemesProp = "jaxr-ebxml.registryBrowser.ConceptsTreeModel.hiddenSchemesList"; String hiddenSchemesStr = ProviderProperties.getInstance().getProperty(hiddenSchemesProp); if (hiddenSchemesStr == null) { filteredSchemes = classSchemes;/* w w w . j av a 2 s .com*/ } else { String[] tokens = hiddenSchemesStr.split("\\|"); if (tokens.length > 0) { filteredSchemes = new ArrayList<ClassificationScheme>(classSchemes); for (int i = 0; i < tokens.length; i++) { String csIdToFilter = tokens[i]; Iterator<?> itr = classSchemes.iterator(); while (itr.hasNext()) { ClassificationScheme cs = (ClassificationScheme) itr.next(); String csId = cs.getKey().getId(); if (csIdToFilter.equalsIgnoreCase(csId)) { filteredSchemes.remove(cs); } } } } } return filteredSchemes; }
From source file:org.ligoj.app.plugin.id.resource.UserOrgResource.java
/** * Merge user groups with this formula : * <ul>// w w w . ja v a2s . c om * <li>DG :Desired groups by current user, and to be set to the entry. These groups must have been previously * checked regarding against the rights the current user has on these groups. So are visible for the principal * user</li> * <li>CG : Current groups of internal entry</li> * <li>VG : Visible groups in CG</li> * <li>WG : Writable groups in VG</li> * <li>GG : Final groups of entry = CG-WG+DG</li> * </ul> * * @param delegates * the available delegates of current principal user. * @param userOrg * The internal user entry to update. * @param groups * The writable groups identifiers to be set to the user in addition of the non visible or writable * groups by the current principal user.. * @return the merged group identifiers to be set internally. */ private Collection<String> mergeGroups(final List<DelegateOrg> delegates, final UserOrg userOrg, final Collection<String> groups) { // Compute the groups merged groups final Collection<String> newGroups = new HashSet<>(userOrg.getGroups()); newGroups.addAll(groups); for (final String oldGroup : userOrg.getGroups()) { final String oldGroupDn = getGroup().findById(oldGroup).getDn(); if (!groups.contains(oldGroup) && canWrite(delegates, oldGroupDn, DelegateType.GROUP)) { // This group is writable, so it has been explicitly removed by // the current user newGroups.remove(oldGroup); } } return newGroups; }
From source file:org.apache.cayenne.modeler.dialog.pref.DataSourcePreferences.java
/** * Tries to establish a DB connection, reporting the status of this * operation./*from www. ja va2 s.c om*/ */ public void testDataSourceAction() { DBConnectionInfo currentDataSource = getConnectionInfo(); if (currentDataSource == null) { return; } if (currentDataSource.getJdbcDriver() == null) { JOptionPane.showMessageDialog(null, "No JDBC Driver specified", "Warning", JOptionPane.WARNING_MESSAGE); return; } if (currentDataSource.getUrl() == null) { JOptionPane.showMessageDialog(null, "No Database URL specified", "Warning", JOptionPane.WARNING_MESSAGE); return; } try { FileClassLoadingService classLoader = new FileClassLoadingService(); List<File> oldPathFiles = ((FileClassLoadingService) getApplication().getClassLoadingService()) .getPathFiles(); Collection<String> details = new ArrayList<>(); for (File oldPathFile : oldPathFiles) { details.add(oldPathFile.getAbsolutePath()); } Preferences classPathPreferences = getApplication().getPreferencesNode(ClasspathPreferences.class, ""); if (editor.getChangedPreferences().containsKey(classPathPreferences)) { Map<String, String> map = editor.getChangedPreferences().get(classPathPreferences); for (Map.Entry<String, String> en : map.entrySet()) { String key = en.getKey(); if (!details.contains(key)) { details.add(key); } } } if (editor.getRemovedPreferences().containsKey(classPathPreferences)) { Map<String, String> map = editor.getRemovedPreferences().get(classPathPreferences); for (Map.Entry<String, String> en : map.entrySet()) { String key = en.getKey(); if (details.contains(key)) { details.remove(key); } } } if (details.size() > 0) { // transform preference to file... Transformer transformer = new Transformer() { public Object transform(Object object) { String pref = (String) object; return new File(pref); } }; classLoader.setPathFiles(CollectionUtils.collect(details, transformer)); } Class<Driver> driverClass = classLoader.loadClass(Driver.class, currentDataSource.getJdbcDriver()); Driver driver = driverClass.newInstance(); // connect via Cayenne DriverDataSource - it addresses some driver // issues... // can't use try with resource here as we can loose meaningful exception Connection c = new DriverDataSource(driver, currentDataSource.getUrl(), currentDataSource.getUserName(), currentDataSource.getPassword()).getConnection(); try { c.close(); } catch (SQLException ignored) { // i guess we can ignore this... } JOptionPane.showMessageDialog(null, "Connected Successfully", "Success", JOptionPane.INFORMATION_MESSAGE); } catch (Throwable th) { th = Util.unwindException(th); String message = "Error connecting to DB: " + th.getLocalizedMessage(); StringTokenizer st = new StringTokenizer(message); StringBuilder sbMessage = new StringBuilder(); int len = 0; String tempString; while (st.hasMoreTokens()) { tempString = st.nextElement().toString(); if (len < 110) { len = len + tempString.length() + 1; } else { sbMessage.append("\n"); len = 0; } sbMessage.append(tempString).append(" "); } JOptionPane.showMessageDialog(null, sbMessage.toString(), "Warning", JOptionPane.WARNING_MESSAGE); } }
From source file:org.apache.usergrid.tools.DupAdminRepair.java
@Override public void runTool(CommandLine line) throws Exception { String outputDir = line.getOptionValue("output"); String emailsDir = String.format("%s/emails", outputDir); String usernamesDir = String.format("%s/usernames", outputDir); createDir(emailsDir);/*from w ww . ja va 2s . c o m*/ createDir(usernamesDir); startSpring(); logger.info("Starting crawl of all admins"); EntityManager em = emf.getEntityManager(CassandraService.MANAGEMENT_APPLICATION_ID); Application app = em.getApplication(); // search for all orgs Query query = new Query(); query.setLimit(PAGE_SIZE); Results r = null; Multimap<String, UUID> emails = HashMultimap.create(); Multimap<String, UUID> usernames = HashMultimap.create(); do { r = em.searchCollection(app, "users", query); for (Entity entity : r.getEntities()) { emails.put(entity.getProperty("email").toString().toLowerCase(), entity.getUuid()); usernames.put(entity.getProperty("username").toString().toLowerCase(), entity.getUuid()); } query.setCursor(r.getCursor()); logger.info("Searching next page"); } while (r != null && r.size() == PAGE_SIZE); // now go through and print out duplicate emails for (String username : usernames.keySet()) { Collection<UUID> ids = usernames.get(username); if (ids.size() > 1) { logger.info("Found multiple users with the username {}", username); // force the username to be reset to the user's email resolveUsernameConflicts(usernamesDir, username, ids); } } for (String email : emails.keySet()) { Collection<UUID> ids = emails.get(email); if (ids.size() > 1) { // get the admin the same way as the rest tier, this way the OTHER // admins will be removed UserInfo targetUser = managementService.getAdminUserByEmail(email); if (targetUser == null) { List<UUID> tempIds = new ArrayList<UUID>(ids); Collections.sort(tempIds); UUID toLoad = tempIds.get(0); logger.warn("Could not load target user by email {}, loading by UUID {} instead", email, toLoad); targetUser = managementService.getAdminUserByUuid(toLoad); ids.remove(toLoad); } UUID targetId = targetUser.getUuid(); ids.remove(targetId); logger.warn("Found multiple admins with the email {}. Retaining uuid {}", email, targetId); FileWriter file = new FileWriter(String.format("%s/%s.all", emailsDir, email)); Map<String, Object> userOrganizationData = managementService.getAdminUserOrganizationData(targetId); file.write(JsonUtils.mapToFormattedJsonString(userOrganizationData)); for (UUID id : ids) { userOrganizationData = managementService.getAdminUserOrganizationData(id); file.write(JsonUtils.mapToFormattedJsonString(userOrganizationData)); file.write("\n\n"); mergeAdmins(emailsDir, id, targetId); } file.flush(); file.close(); // force the index update after all other admins have been merged logger.info("Forcing re-index of admin with email {} and id {}", email, targetId); User targetUserEntity = em.get(targetUser.getUuid(), User.class); em.update(targetUserEntity); FileWriter merged = new FileWriter(String.format("%s/%s.merged", emailsDir, email)); userOrganizationData = managementService.getAdminUserOrganizationData(targetUser.getUuid()); merged.write(JsonUtils.mapToFormattedJsonString(userOrganizationData)); merged.flush(); merged.close(); } } logger.info("Repair complete"); }
From source file:org.sparkcommerce.openadmin.server.service.persistence.module.BasicPersistenceModule.java
@Override public void remove(PersistencePackage persistencePackage) throws ServiceException { Entity entity = persistencePackage.getEntity(); PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective(); ForeignKey foreignKey = (ForeignKey) persistencePerspective.getPersistencePerspectiveItems() .get(PersistencePerspectiveItemType.FOREIGNKEY); if (foreignKey != null && !foreignKey.getMutable()) { throw new SecurityServiceException("Entity not mutable"); }/* w w w.j a va 2 s. c o m*/ try { Class<?>[] entities = persistenceManager .getPolymorphicEntities(persistencePackage.getCeilingEntityFullyQualifiedClassname()); Map<String, FieldMetadata> mergedUnfilteredProperties = persistenceManager.getDynamicEntityDao() .getMergedProperties(persistencePackage.getCeilingEntityFullyQualifiedClassname(), entities, foreignKey, persistencePerspective.getAdditionalNonPersistentProperties(), persistencePerspective.getAdditionalForeignKeys(), MergedPropertyType.PRIMARY, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), ""); Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(mergedUnfilteredProperties); Object primaryKey = getPrimaryKey(entity, mergedProperties); Serializable instance = persistenceManager.getDynamicEntityDao() .retrieve(Class.forName(entity.getType()[0]), primaryKey); Assert.isTrue(instance != null, "Entity not found"); switch (persistencePerspective.getOperationTypes().getRemoveType()) { case NONDESTRUCTIVEREMOVE: FieldManager fieldManager = getFieldManager(); FieldMetadata manyToFieldMetadata = mergedUnfilteredProperties.get(foreignKey.getManyToField()); Object foreignKeyValue = entity.getPMap().get(foreignKey.getManyToField()).getValue(); try { foreignKeyValue = Long.valueOf((String) foreignKeyValue); } catch (NumberFormatException e) { LOG.warn("Foreign primary key is not of type Long, assuming String for remove lookup"); } Serializable foreignInstance = persistenceManager.getDynamicEntityDao() .retrieve(Class.forName(foreignKey.getForeignKeyClass()), foreignKeyValue); Collection collection = (Collection) fieldManager.getFieldValue(foreignInstance, foreignKey.getOriginatingField()); collection.remove(instance); // if this is a bi-directional @OneToMany/@ManyToOne and there is no @JoinTable (just a foreign key on // the @ManyToOne side) then it will not be updated. In that instance, we have to explicitly // set the manyTo field to null so that subsequent lookups will not find it if (manyToFieldMetadata instanceof BasicFieldMetadata) { if (BooleanUtils.isTrue(((BasicFieldMetadata) manyToFieldMetadata).getRequired())) { throw new ServiceException("Could not remove from the collection as the ManyToOne side is a" + " non-optional relationship. Consider changing 'optional=true' in the @ManyToOne annotation" + " or nullable=true within the @JoinColumn annotation"); } Field manyToField = fieldManager.getField(instance.getClass(), foreignKey.getManyToField()); Object manyToObject = manyToField.get(instance); if (manyToObject != null && !(manyToObject instanceof Collection) && !(manyToObject instanceof Map)) { manyToField.set(instance, null); instance = persistenceManager.getDynamicEntityDao().merge(instance); } } break; case BASIC: persistenceManager.getDynamicEntityDao().remove(instance); break; } } catch (Exception e) { throw new ServiceException("Problem removing entity : " + e.getMessage(), e); } }
From source file:gate.annotation.AnnotationSetImpl.java
/** Remove from the offset indices. */ protected void removeFromOffsetIndex(Annotation a) { if (nodesByOffset != null) { // knowing when a node is no longer needed would require keeping a // reference // count on annotations, or using a weak reference to the nodes in // nodesByOffset }//from www. jav a2 s .c om if (annotsByStartNode != null) { Integer id = a.getStartNode().getId(); // might be an annotation or an annotationset Object objectAtNode = annotsByStartNode.get(id); if (objectAtNode instanceof Annotation) { annotsByStartNode.remove(id); // no annotations start here any // more return; } // otherwise it is a Collection @SuppressWarnings("unchecked") Collection<Annotation> starterAnnots = (Collection<Annotation>) objectAtNode; starterAnnots.remove(a); // if there is only one annotation left // we discard the set and put directly the annotation if (starterAnnots.size() == 1) annotsByStartNode.put(id, starterAnnots.iterator().next()); } }
From source file:org.lockss.test.LockssTestCase.java
/** Assert that a collection cannot be modified, <i>ie</i>, that all of * the following methods, plus the collection's iterator().remove() * method, throw UnsupportedOperationException: add(), addAll(), clear(), * remove(), removeAll(), retainAll() */ public static void assertUnmodifiable(Collection coll) { List list = ListUtil.list("bar"); try {/*from ww w . j ava 2 s .c o m*/ coll.add("foo"); fail("add() didn't throw"); } catch (UnsupportedOperationException e) { } try { coll.addAll(list); fail("addAll() didn't throw"); } catch (UnsupportedOperationException e) { } try { coll.clear(); fail("clear() didn't throw"); } catch (UnsupportedOperationException e) { } try { coll.remove("foo"); fail("remove() didn't throw"); } catch (UnsupportedOperationException e) { } try { coll.removeAll(list); fail("removeAll() didn't throw"); } catch (UnsupportedOperationException e) { } try { coll.retainAll(list); fail("retainAll() didn't throw"); } catch (UnsupportedOperationException e) { } Iterator iter = coll.iterator(); iter.next(); try { iter.remove(); fail("iterator().remove() didn't throw"); } catch (UnsupportedOperationException e) { } }