List of usage examples for java.util Collection containsAll
boolean containsAll(Collection<?> c);
From source file:ubic.basecode.io.reader.DoubleMatrixReader.java
/** * @param stream InputStream/*from w ww . jav a 2 s . co m*/ * @param wantedRowNames Set * @param createEmptyRows if a row contained in <code>wantedRowNames</code> is not found in the file, create an * empty row filled with Double.NaN iff this param is true. * @param maxRows * @return matrix * @throws IOException */ @SuppressWarnings("resource") public DoubleMatrix<String, String> read(InputStream stream, Collection<String> wantedRowNames, boolean createEmptyRows, int skipColumns, int maxRows) throws IOException { BufferedReader dis = new BufferedReader(new InputStreamReader(stream)); List<DoubleArrayList> MTemp = new Vector<DoubleArrayList>(); List<String> rowNames = new Vector<String>(); String row; // // We need to keep track of which row names we actually found in the file // because will want to add empty rows for each row name we didn't find // (if createEmptyRows == true). // Collection<String> wantedRowsFound = new HashSet<String>(); colNames = readHeader(dis, skipColumns); numHeadings = colNames.size(); int rowNumber = 0; while ((row = dis.readLine()) != null) { if (StringUtils.isBlank(row)) { continue; } String rowName = parseRow(row, rowNames, MTemp, wantedRowNames, skipColumns); if (rowName == null) { // signals a blank or skipped row. continue; } if (wantedRowNames != null) { // if we already have all the rows we want, then bail out if (wantedRowsFound.size() >= wantedRowNames.size()) { assert wantedRowsFound.containsAll(wantedRowNames); log.info("Found all rows needed"); return createMatrix(MTemp, rowNames, colNames); } if (wantedRowNames.contains(rowName)) { wantedRowsFound.add(rowName); } } if (maxRows > 0 && ++rowNumber == maxRows) break; } stream.close(); // // Add empty rows for each row name we didn't find in the file // if (wantedRowNames != null && wantedRowNames.size() != wantedRowsFound.size() && createEmptyRows) { Iterator<String> iterator = wantedRowNames.iterator(); while (iterator.hasNext()) { String s = iterator.next(); if (!wantedRowsFound.contains(s)) { if (log.isDebugEnabled()) log.debug(s + " was not found, adding empty row"); DoubleArrayList emptyRow = createEmptyRow(numHeadings); rowNames.add(s); MTemp.add(emptyRow); } } } assert rowNames.size() == MTemp.size(); return createMatrix(MTemp, rowNames, colNames); }
From source file:org.topazproject.otm.impl.SessionFactoryImpl.java
private boolean isAcceptable(ClassMetadata cm, ClassMetadata clazz, EntityMode mode, Collection<String> typeUris) { // assignable test if ((clazz != null) && !clazz.isAssignableFrom(cm, mode)) return false; // type membership test if (!typeUris.containsAll(cm.getTypes())) return false; // instantiability test if ((mode != null) && !cm.getEntityBinder(mode).isInstantiable()) return false; return true;// w ww .ja v a 2 s . c o m }
From source file:org.apache.lens.cube.parse.join.AutoJoinContext.java
/** * Prunes the join chains defined in Cube whose starting column is not there in any of the candidate facts. * Same is done in case of join paths defined in Dimensions. * * @param cube/*w w w.j a v a 2 s . co m*/ * @param dimsToQuery * @throws LensException */ public void pruneAllPaths(CubeInterface cube, Collection<String> candColumns, final Map<Dimension, CandidateDim> dimsToQuery) throws LensException { // Remove join paths which cannot be satisfied by the resolved candidate // fact and dimension tables // include columns from picked candidate for (List<JoinPath> paths : allPaths.values()) { for (int i = 0; i < paths.size(); i++) { JoinPath jp = paths.get(i); List<String> cubeCols = jp.getColumnsForTable((AbstractCubeTable) cube); if (cubeCols != null && !candColumns.containsAll(cubeCols)) { // This path requires some columns from the cube which are not // present in the candidate fact // Remove this path log.info("Removing join path:{} as columns :{} dont exist", jp, cubeCols); paths.remove(i); i--; } } } pruneEmptyPaths(allPaths); pruneAllPaths(dimsToQuery); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServices.java
private void checkForApproval(String userid, String clientId, Collection<String> requestedScopes, Collection<String> autoApprovedScopes) { if (autoApprovedScopes.containsAll(requestedScopes)) { return;/*from ww w.ja v a 2 s. c o m*/ } Set<String> approvedScopes = new HashSet<>(autoApprovedScopes); // Search through the users approvals for scopes that are requested, not // auto approved, not expired, // not DENIED and not approved more recently than when this access token // was issued. List<Approval> approvals = approvalStore.getApprovals(userid, clientId); for (Approval approval : approvals) { if (requestedScopes.contains(approval.getScope()) && approval.getStatus() == ApprovalStatus.APPROVED) { if (!approval.isCurrentlyActive()) { logger.debug("Approval " + approval + " has expired. Need to re-approve."); throw new InvalidTokenException("Invalid token (approvals expired)"); } approvedScopes.add(approval.getScope()); } } // Only issue the token if all the requested scopes have unexpired // approvals made before the refresh token was // issued OR if those scopes are auto approved if (!approvedScopes.containsAll(requestedScopes)) { logger.debug("All requested scopes " + requestedScopes + " were not approved " + approvedScopes); Set<String> unapprovedScopes = new HashSet<String>(requestedScopes); unapprovedScopes.removeAll(approvedScopes); throw new InvalidTokenException( "Invalid token (some requested scopes are not approved): " + unapprovedScopes); } }
From source file:ubic.gemma.persistence.util.EntityUtils.java
/** * Expert use only. Used to expose some ACL information to the DAO layer (normally this happens in an interceptor). * * @param sess session/*from ww w . j av a 2 s . c o m*/ * @param securedClass Securable type * @param ids to be filtered * @param showPublic also show public items (won't work if showOnlyEditable is true) * @param showOnlyEditable show only editable * @return filtered IDs, at the very least limited to those that are readable by the current user */ public static Collection<Long> securityFilterIds(Class<? extends Securable> securedClass, Collection<Long> ids, boolean showOnlyEditable, boolean showPublic, Session sess) { if (ids.isEmpty()) return ids; if (SecurityUtil.isUserAdmin()) { return ids; } /* * Find groups user is a member of */ String userName = SecurityUtil.getCurrentUsername(); boolean isAnonymous = SecurityUtil.isUserAnonymous(); if (isAnonymous && (showOnlyEditable || !showPublic)) { return new HashSet<>(); } String queryString = "select aoi.OBJECT_ID"; queryString += " from ACLOBJECTIDENTITY aoi"; queryString += " join ACLENTRY ace on ace.OBJECTIDENTITY_FK = aoi.ID "; queryString += " join ACLSID sid on sid.ID = aoi.OWNER_SID_FK "; queryString += " where aoi.OBJECT_ID in (:ids)"; queryString += " and aoi.OBJECT_CLASS = :clazz and "; queryString += EntityUtils.addGroupAndUserNameRestriction(showOnlyEditable, showPublic); // will be empty if anonymous //noinspection unchecked Collection<String> groups = sess.createQuery( "select ug.name from UserGroup ug inner join ug.groupMembers memb where memb.userName = :user") .setParameter("user", userName).list(); Query query = sess.createSQLQuery(queryString).setParameter("clazz", securedClass.getName()) .setParameterList("ids", ids); if (queryString.contains(":groups")) { query.setParameterList("groups", groups); } if (queryString.contains(":userName")) { query.setParameter("userName", userName); } //noinspection unchecked List<BigInteger> r = query.list(); Set<Long> rl = new HashSet<>(); for (BigInteger bi : r) { rl.add(bi.longValue()); } if (!ids.containsAll(rl)) { // really an assertion, but being extra-careful throw new SecurityException("Security filter failure"); } return rl; }
From source file:com.facebook.model.GraphObjectFactoryTests.java
@SmallTest @MediumTest/*from w w w .ja v a 2 s . c o m*/ @LargeTest public void testCollectionContainsAll() throws JSONException { JSONArray array = new JSONArray(); array.put(5); array.put(-1); Collection<Integer> collection = GraphObject.Factory.createList(array, Integer.class); assertTrue(collection.containsAll(Arrays.asList(5))); assertTrue(collection.containsAll(Arrays.asList(5, -1))); assertFalse(collection.containsAll(Arrays.asList(5, -1, 2))); }
From source file:Main.java
public static boolean containsAll(Collection a, Collection b) { // fast paths if (a == b)/* w ww. j av a 2s .c om*/ return true; if (b.size() == 0) return true; if (a.size() < b.size()) return false; if (a instanceof SortedSet && b instanceof SortedSet) { SortedSet aa = (SortedSet) a; SortedSet bb = (SortedSet) b; Comparator bbc = bb.comparator(); Comparator aac = aa.comparator(); if (bbc == null && aac == null) { Iterator ai = aa.iterator(); Iterator bi = bb.iterator(); Comparable ao = (Comparable) ai.next(); // these are ok, since the sizes are != 0 Comparable bo = (Comparable) bi.next(); while (true) { int rel = ao.compareTo(bo); if (rel == 0) { if (!bi.hasNext()) return true; if (!ai.hasNext()) return false; bo = (Comparable) bi.next(); ao = (Comparable) ai.next(); } else if (rel < 0) { if (!ai.hasNext()) return false; ao = (Comparable) ai.next(); } else { return false; } } } else if (bbc.equals(aac)) { Iterator ai = aa.iterator(); Iterator bi = bb.iterator(); Object ao = ai.next(); // these are ok, since the sizes are != 0 Object bo = bi.next(); while (true) { int rel = aac.compare(ao, bo); if (rel == 0) { if (!bi.hasNext()) return true; if (!ai.hasNext()) return false; bo = bi.next(); ao = ai.next(); } else if (rel < 0) { if (!ai.hasNext()) return false; ao = ai.next(); } else { return false; } } } } return a.containsAll(b); }
From source file:org.apache.mahout.ga.watchmaker.cd.tool.CDInfosToolTest.java
@Test public void testGatherInfos() throws Exception { int n = 1; // put a greater value when you search for some nasty bug for (int nloop = 0; nloop < n; nloop++) { int maxattr = 100; // max number of attributes int nbattrs = rng.nextInt(maxattr) + 1; // random descriptors double numRate = rng.nextDouble(); double catRate = rng.nextDouble() * (1.0 - numRate); Descriptors descriptors = randomDescriptors(nbattrs, numRate, catRate); // random descriptions Object[][] descriptions = randomDescriptions(descriptors); // random dataset Path inpath = getTestTempDirPath("input"); Path output = getTestTempDirPath("output"); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(inpath.toUri(), conf); HadoopUtil.delete(conf, inpath); randomDataset(fs, inpath, descriptors, descriptions); // Start the tool List<String> result = Lists.newArrayList(); fs.delete(output, true); // It's unhappy if this directory exists CDInfosTool.gatherInfos(descriptors, inpath, output, result); // check the results Collection<String> target = Lists.newArrayList(); assertEquals(nbNonIgnored(descriptors), result.size()); int rindex = 0; for (int index = 0; index < nbattrs; index++) { if (descriptors.isIgnored(index)) { continue; }/*from ww w .j a va2 s . co m*/ String description = result.get(rindex++); if (descriptors.isNumerical(index)) { // numerical attribute double min = (Double) descriptions[index][0]; double max = (Double) descriptions[index][1]; double[] range = DescriptionUtils.extractNumericalRange(description); assertTrue("bad min value for attribute (" + index + ')', min <= range[0]); assertTrue("bad max value for attribute (" + index + ')', max >= range[1]); } else if (descriptors.isNominal(index)) { // categorical attribute Object[] values = descriptions[index]; target.clear(); DescriptionUtils.extractNominalValues(description, target); assertEquals(values.length, target.size()); assertTrue(target.containsAll(Arrays.asList(values))); } } } }
From source file:ubic.gemma.analysis.expression.diff.DifferentialExpressionAnalyzerServiceImpl.java
/** * @param expressionExperiment/* w w w . j a va2 s. c om*/ * @param newAnalysis * @param factors * @return */ protected int deleteOldAnalyses(ExpressionExperiment expressionExperiment, DifferentialExpressionAnalysis newAnalysis, Collection<ExperimentalFactor> factors) { Collection<DifferentialExpressionAnalysis> diffAnalyses = differentialExpressionAnalysisService .findByInvestigation(expressionExperiment); int numDeleted = 0; if (diffAnalyses == null || diffAnalyses.isEmpty()) { log.info("No differential expression analyses to delete for " + expressionExperiment.getShortName()); return numDeleted; } this.differentialExpressionAnalysisService.thaw(diffAnalyses); for (DifferentialExpressionAnalysis existingAnalysis : diffAnalyses) { Collection<ExperimentalFactor> factorsInAnalysis = new HashSet<ExperimentalFactor>(); for (ExpressionAnalysisResultSet resultSet : existingAnalysis.getResultSets()) { factorsInAnalysis.addAll(resultSet.getExperimentalFactors()); } FactorValue subsetFactorValueForExisting = existingAnalysis.getSubsetFactorValue(); /* * Match if: factors are the same, and if this is a subset, it's the same subset factorvalue. */ if (factorsInAnalysis.size() == factors.size() && factorsInAnalysis.containsAll(factors) && (subsetFactorValueForExisting == null || subsetFactorValueForExisting.equals(newAnalysis.getSubsetFactorValue()))) { log.info("Deleting analysis with ID=" + existingAnalysis.getId()); deleteAnalysis(expressionExperiment, existingAnalysis); numDeleted++; } } if (numDeleted == 0) { log.info("None of the other existing analyses were eligible for deletion"); } return numDeleted; }