List of usage examples for java.util Collection containsAll
boolean containsAll(Collection<?> c);
From source file:org.intermine.bio.web.export.SequenceExporter.java
/** * Set the header to be the contents of row, separated by spaces. *//*from w w w .ja va2 s . c o m*/ private void makeHeader(StringBuffer header, Object object, List<ResultElement> row, Collection<Path> unionPathCollection, Collection<Path> newPathCollection) { List<String> headerBits = new ArrayList<String>(); // add the Object's (Protein or LocatedSequenceFeature) // primaryIdentifier at the first place // in the header Object keyFieldValue = ClassKeyHelper.getKeyFieldValue((FastPathObject) object, this.classKeys); if (keyFieldValue != null) { headerBits.add(keyFieldValue.toString()); } else { headerBits.add("-"); } // List<Object> keyFieldValues = // ClassKeyHelper.getKeyFieldValues((FastPathObject) object, this.classKeys); // for (Object key : keyFieldValues) { // if (key != null) { // headerBits.add(key.toString()); // } // } // here unionPathCollection is newPathCollection List<ResultElement> subRow = new ArrayList<ResultElement>(); if (newPathCollection != null && unionPathCollection != null && unionPathCollection.containsAll(newPathCollection)) { for (Path p : newPathCollection) { if (!p.toString().endsWith(".id")) { subRow.add(row.get(((List<Path>) unionPathCollection).indexOf(p))); } } } else { subRow = row; } // two instances if (object instanceof SequenceFeature) { // add the sequence location info at the second place in the header SequenceFeature feature = (SequenceFeature) object; Location loc = feature.getChromosomeLocation(); if (loc == null) { headerBits.add("-"); } else { // Assume if loc exits, the following information should be available String chr = loc.getLocatedOn().getPrimaryIdentifier(); Integer start = loc.getStart(); Integer end = loc.getEnd(); String locString = chr + ':' + start + '-' + end; headerBits.add(locString); } if (extension > 0) { headerBits.add("extension:" + extension + "bp"); } for (ResultElement re : subRow) { // to avoid failure in modmine when no experimental factors (sub 2745) if (re == null) { continue; } // Disable collection export until further bug diagnose if (re.getPath().containsCollections()) { continue; } Object fieldValue = re.getField(); if (fieldValue == null) { headerBits.add("-"); } else if (fieldValue.toString().equals(keyFieldValue) || (re.getObject() instanceof Location) || (re.getObject() instanceof Chromosome)) { // ignore the primaryIdentifier and Location in // ResultElement continue; } else { headerBits.add(fieldValue.toString()); } } } else if (object instanceof Protein) { for (ResultElement re : subRow) { if (re == null) { continue; } // Disable collection export until further bug diagnose if (re.getPath().containsCollections()) { continue; } Object fieldValue = re.getField(); if (fieldValue == null) { headerBits.add("-"); } else if (fieldValue.toString().equals(keyFieldValue)) { continue; } else { headerBits.add(fieldValue.toString()); } } } header.append(StringUtil.join(headerBits, " ")); }
From source file:org.slc.sli.api.service.BasicService.java
/** * Determines if the user has multiple contexts, or differing sets of rights per role. * * @return Whether or not the user has multiple contexts, or differing sets of rights per role *//*from www. j a v a 2s .co m*/ protected boolean userHasMultipleContextsOrDifferingRights() { if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) { return true; } SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (principal.getEdOrgRights().size() > 1) { Iterator<Collection<GrantedAuthority>> edOrgRightsIter = principal.getEdOrgRights().values().iterator(); Collection<GrantedAuthority> firstRightsSet = edOrgRightsIter.next(); while (edOrgRightsIter.hasNext()) { Collection<GrantedAuthority> nextRightsSet = edOrgRightsIter.next(); if ((!firstRightsSet.containsAll(nextRightsSet)) || (!nextRightsSet.containsAll(firstRightsSet))) { return true; } } } return false; }
From source file:org.ejbca.core.model.era.RaMasterApiSessionBean.java
@Override public CertificateDataWrapper searchForCertificate(final AuthenticationToken authenticationToken, final String fingerprint) { final CertificateDataWrapper cdw = certificateStoreSession.getCertificateData(fingerprint); if (cdw == null) { return null; }//w ww .j av a 2 s.c o m if (!caSession.authorizedToCANoLogging(authenticationToken, cdw.getCertificateData().getIssuerDN().hashCode())) { return null; } // Check EEP authorization (allow an highly privileged admin, e.g. superadmin, that can access all profiles to ignore this check // so certificates can still be accessed by this admin even after a EEP has been removed. final Collection<Integer> authorizedEepIds = new ArrayList<>(endEntityProfileSession .getAuthorizedEndEntityProfileIds(authenticationToken, AccessRulesConstants.VIEW_END_ENTITY)); final boolean accessAnyEepAvailable = authorizedEepIds .containsAll(endEntityProfileSession.getEndEntityProfileIdToNameMap().keySet()); if (!accessAnyEepAvailable && !authorizedEepIds .contains(Integer.valueOf(cdw.getCertificateData().getEndEntityProfileIdOrZero()))) { return null; } return cdw; }
From source file:com.evolveum.midpoint.prism.delta.ItemDelta.java
private boolean containsSet(Collection<V> thisSet, Collection<V> otherSet) { if (thisSet == null && otherSet == null) { return true; }// w w w. j a v a 2 s . c o m if (otherSet == null) { return true; } if (thisSet == null) { return false; } return thisSet.containsAll(otherSet); }
From source file:com.davidsoergel.trees.AbstractRootedPhylogeny.java
/** * {@inheritDoc}/* w ww .j a va 2 s. co m*/ */ @NotNull public BasicRootedPhylogeny<T> extractTreeWithLeafIDs(Set<T> ids, boolean ignoreAbsentNodes, boolean includeInternalBranches, MutualExclusionResolutionMode mode) throws NoSuchNodeException //, NodeNamer<T> namer { /*try { if (getLeafValues().equals(ids) && includeInternalBranches) { return this; } } catch (TreeRuntimeException e) { // the actual tree is expensive to load (e.g. NcbiTaxonomyService) so getLeafValues is a bad idea // OK, just do the explicit extraction anyway then } */ /* List<PhylogenyNode<T>> theLeaves = idsToLeaves(ids, ignoreAbsentNodes); if (theLeaves.isEmpty()) { throw new NoSuchNodeException("No leaves found for ids: " + ids); } RootedPhylogeny<T> result = extractTreeWithLeaves(theLeaves, includeInternalBranches, mode); */ Set<List<? extends PhylogenyNode<T>>> theDisposableLeafPaths = idsToDisposableBasicLeafPaths(ids, ignoreAbsentNodes); if (theDisposableLeafPaths.isEmpty()) { throw new NoSuchNodeException("No leaves found for ids: " + ids); } BasicRootedPhylogeny<T> result = extractTreeWithLeafPaths(theDisposableLeafPaths, includeInternalBranches, mode); Collection<T> gotLeaves = result.getLeafValues(); Collection<T> gotNodes = result.getNodeValues(); // all the leaves that were found were leaves that were requested assert ids.containsAll(gotLeaves); // BAD confusing interaction between all three parameters //if (includeInternalBranches && !ignoreAbsentNodes) //(mode == MutualExclusionResolutionMode.LEAF || mode == MutualExclusionResolutionMode.BOTH)) if (!ignoreAbsentNodes) { // some requested leaves may turn out to be internal nodes, but at least they should all be accounted for assert gotNodes.containsAll(ids); } /* if (!ignoreAbsentNodes) { // any requested leaves that turned out to be internal nodes should have had a phantom leaf added assert gotLeaves.containsAll(ids); } */ return result; }
From source file:org.ejbca.core.model.era.RaMasterApiSessionBean.java
@SuppressWarnings("unchecked") @Override/*from w w w .j a v a2 s . co m*/ public RaEndEntitySearchResponse searchForEndEntities(AuthenticationToken authenticationToken, RaEndEntitySearchRequest request) { final RaEndEntitySearchResponse response = new RaEndEntitySearchResponse(); final List<Integer> authorizedLocalCaIds = new ArrayList<>( caSession.getAuthorizedCaIds(authenticationToken)); // Only search a subset of the requested CAs if requested if (!request.getCaIds().isEmpty()) { authorizedLocalCaIds.retainAll(request.getCaIds()); } if (authorizedLocalCaIds.isEmpty()) { // Empty response since there were no authorized CAs if (log.isDebugEnabled()) { log.debug("Client '" + authenticationToken + "' was not authorized to any of the requested CAs and the search request will be dropped."); } return response; } // Check Certificate Profile authorization final List<Integer> authorizedCpIds = new ArrayList<>( certificateProfileSession.getAuthorizedCertificateProfileIds(authenticationToken, 0)); final boolean accessAnyCpAvailable = authorizedCpIds .containsAll(certificateProfileSession.getCertificateProfileIdToNameMap().keySet()); if (!request.getCpIds().isEmpty()) { authorizedCpIds.retainAll(request.getCpIds()); } if (authorizedCpIds.isEmpty()) { // Empty response since there were no authorized Certificate Profiles if (log.isDebugEnabled()) { log.debug("Client '" + authenticationToken + "' was not authorized to any of the requested CPs and the search request will be dropped."); } return response; } // Check End Entity Profile authorization final Collection<Integer> authorizedEepIds = new ArrayList<>(endEntityProfileSession .getAuthorizedEndEntityProfileIds(authenticationToken, AccessRulesConstants.VIEW_END_ENTITY)); final boolean accessAnyEepAvailable = authorizedEepIds .containsAll(endEntityProfileSession.getEndEntityProfileIdToNameMap().keySet()); if (!request.getEepIds().isEmpty()) { authorizedEepIds.retainAll(request.getEepIds()); } if (authorizedEepIds.isEmpty()) { // Empty response since there were no authorized End Entity Profiles if (log.isDebugEnabled()) { log.debug("Client '" + authenticationToken + "' was not authorized to any of the requested EEPs and the search request will be dropped."); } return response; } final String subjectDnSearchString = request.getSubjectDnSearchString(); final String subjectAnSearchString = request.getSubjectAnSearchString(); final String usernameSearchString = request.getUsernameSearchString(); final StringBuilder sb = new StringBuilder("SELECT a.username FROM UserData a WHERE (a.caId IN (:caId))"); if (!subjectDnSearchString.isEmpty() || !subjectAnSearchString.isEmpty() || !usernameSearchString.isEmpty()) { sb.append(" AND ("); boolean firstAppended = false; if (!subjectDnSearchString.isEmpty()) { sb.append("a.subjectDN LIKE :subjectDN"); firstAppended = true; } if (!subjectAnSearchString.isEmpty()) { if (firstAppended) { sb.append(" OR "); } else { firstAppended = true; } sb.append("a.subjectAltName LIKE :subjectAltName"); } if (!usernameSearchString.isEmpty()) { if (firstAppended) { sb.append(" OR "); } else { firstAppended = true; } sb.append("a.username LIKE :username"); } sb.append(")"); } if (request.isModifiedAfterUsed()) { sb.append(" AND (a.timeModified > :modifiedAfter)"); } if (request.isModifiedBeforeUsed()) { sb.append(" AND (a.timeModified < :modifiedBefore)"); } if (!request.getStatuses().isEmpty()) { sb.append(" AND (a.status IN (:status))"); } // Don't constrain results to certain end entity profiles if root access is available and "any" CP is requested if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) { sb.append(" AND (a.certificateProfileId IN (:certificateProfileId))"); } // Don't constrain results to certain end entity profiles if root access is available and "any" EEP is requested if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) { sb.append(" AND (a.endEntityProfileId IN (:endEntityProfileId))"); } final Query query = entityManager.createQuery(sb.toString()); query.setParameter("caId", authorizedLocalCaIds); if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) { query.setParameter("certificateProfileId", authorizedCpIds); } if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) { query.setParameter("endEntityProfileId", authorizedEepIds); } if (log.isDebugEnabled()) { log.debug(" CA IDs: " + Arrays.toString(authorizedLocalCaIds.toArray())); if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) { log.debug(" certificateProfileId: " + Arrays.toString(authorizedCpIds.toArray())); } else { log.debug(" certificateProfileId: Any (even deleted) profile(s) due to root access."); } if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) { log.debug(" endEntityProfileId: " + Arrays.toString(authorizedEepIds.toArray())); } else { log.debug(" endEntityProfileId: Any (even deleted) profile(s) due to root access."); } } if (!subjectDnSearchString.isEmpty()) { if (request.isSubjectDnSearchExact()) { query.setParameter("subjectDN", subjectDnSearchString); } else { query.setParameter("subjectDN", "%" + subjectDnSearchString + "%"); } } if (!subjectAnSearchString.isEmpty()) { if (request.isSubjectAnSearchExact()) { query.setParameter("subjectAltName", subjectAnSearchString); } else { query.setParameter("subjectAltName", "%" + subjectAnSearchString + "%"); } } if (!usernameSearchString.isEmpty()) { if (request.isUsernameSearchExact()) { query.setParameter("username", usernameSearchString); } else { query.setParameter("username", "%" + usernameSearchString + "%"); } } if (request.isModifiedAfterUsed()) { query.setParameter("modifiedAfter", request.getModifiedAfter()); } if (request.isModifiedBeforeUsed()) { query.setParameter("modifiedBefore", request.getModifiedBefore()); } if (!request.getStatuses().isEmpty()) { query.setParameter("status", request.getStatuses()); } final int maxResults = Math.min(getGlobalCesecoreConfiguration().getMaximumQueryCount(), request.getMaxResults()); query.setMaxResults(maxResults); /* Try to use the non-portable hint (depends on DB and JDBC driver) to specify how long in milliseconds the query may run. Possible behaviors: * - The hint is ignored * - A QueryTimeoutException is thrown * - A PersistenceException is thrown (and the transaction which don't have here is marked for roll-back) */ final long queryTimeout = getGlobalCesecoreConfiguration().getMaximumQueryTimeout(); if (queryTimeout > 0L) { query.setHint("javax.persistence.query.timeout", String.valueOf(queryTimeout)); } final List<String> usernames; try { usernames = query.getResultList(); for (final String username : usernames) { response.getEndEntities().add(endEntityAccessSession.findUser(username)); } response.setMightHaveMoreResults(usernames.size() == maxResults); if (log.isDebugEnabled()) { log.debug("Certificate search query: " + sb.toString() + " LIMIT " + maxResults + " \u2192 " + usernames.size() + " results. queryTimeout=" + queryTimeout + "ms"); } } catch (QueryTimeoutException e) { log.info("Requested search query by " + authenticationToken + " took too long. Query was " + e.getQuery().toString() + ". " + e.getMessage()); response.setMightHaveMoreResults(true); } catch (PersistenceException e) { log.info("Requested search query by " + authenticationToken + " failed, possibly due to timeout. " + e.getMessage()); response.setMightHaveMoreResults(true); } return response; }
From source file:org.ejbca.core.model.era.RaMasterApiSessionBean.java
@SuppressWarnings("unchecked") @Override/*from w w w .j a va 2 s. co m*/ public RaCertificateSearchResponse searchForCertificates(AuthenticationToken authenticationToken, RaCertificateSearchRequest request) { final RaCertificateSearchResponse response = new RaCertificateSearchResponse(); final List<Integer> authorizedLocalCaIds = new ArrayList<>( caSession.getAuthorizedCaIds(authenticationToken)); // Only search a subset of the requested CAs if requested if (!request.getCaIds().isEmpty()) { authorizedLocalCaIds.retainAll(request.getCaIds()); } final List<String> issuerDns = new ArrayList<>(); for (final int caId : authorizedLocalCaIds) { try { final String issuerDn = CertTools .stringToBCDNString(StringTools.strip(caSession.getCAInfoInternal(caId).getSubjectDN())); issuerDns.add(issuerDn); } catch (CADoesntExistsException e) { log.warn("CA went missing during search operation. " + e.getMessage()); } } if (issuerDns.isEmpty()) { // Empty response since there were no authorized CAs if (log.isDebugEnabled()) { log.debug("Client '" + authenticationToken + "' was not authorized to any of the requested CAs and the search request will be dropped."); } return response; } // Check Certificate Profile authorization final List<Integer> authorizedCpIds = new ArrayList<>( certificateProfileSession.getAuthorizedCertificateProfileIds(authenticationToken, 0)); final boolean accessAnyCpAvailable = authorizedCpIds .containsAll(certificateProfileSession.getCertificateProfileIdToNameMap().keySet()); if (!request.getCpIds().isEmpty()) { authorizedCpIds.retainAll(request.getCpIds()); } if (authorizedCpIds.isEmpty()) { // Empty response since there were no authorized Certificate Profiles if (log.isDebugEnabled()) { log.debug("Client '" + authenticationToken + "' was not authorized to any of the requested CPs and the search request will be dropped."); } return response; } // Check End Entity Profile authorization final Collection<Integer> authorizedEepIds = new ArrayList<>(endEntityProfileSession .getAuthorizedEndEntityProfileIds(authenticationToken, AccessRulesConstants.VIEW_END_ENTITY)); final boolean accessAnyEepAvailable = authorizedEepIds .containsAll(endEntityProfileSession.getEndEntityProfileIdToNameMap().keySet()); if (!request.getEepIds().isEmpty()) { authorizedEepIds.retainAll(request.getEepIds()); } if (authorizedEepIds.isEmpty()) { // Empty response since there were no authorized End Entity Profiles if (log.isDebugEnabled()) { log.debug("Client '" + authenticationToken + "' was not authorized to any of the requested EEPs and the search request will be dropped."); } return response; } final String subjectDnSearchString = request.getSubjectDnSearchString(); final String subjectAnSearchString = request.getSubjectAnSearchString(); final String usernameSearchString = request.getUsernameSearchString(); final String serialNumberSearchStringFromDec = request.getSerialNumberSearchStringFromDec(); final String serialNumberSearchStringFromHex = request.getSerialNumberSearchStringFromHex(); final StringBuilder sb = new StringBuilder( "SELECT a.fingerprint FROM CertificateData a WHERE (a.issuerDN IN (:issuerDN))"); if (!subjectDnSearchString.isEmpty() || !subjectAnSearchString.isEmpty() || !usernameSearchString.isEmpty() || !serialNumberSearchStringFromDec.isEmpty() || !serialNumberSearchStringFromHex.isEmpty()) { sb.append(" AND ("); boolean firstAppended = false; if (!subjectDnSearchString.isEmpty()) { sb.append("a.subjectDN LIKE :subjectDN"); firstAppended = true; } if (!subjectAnSearchString.isEmpty()) { if (firstAppended) { sb.append(" OR "); } else { firstAppended = true; } sb.append("a.subjectAltName LIKE :subjectAltName"); } if (!usernameSearchString.isEmpty()) { if (firstAppended) { sb.append(" OR "); } else { firstAppended = true; } sb.append("a.username LIKE :username"); } if (!serialNumberSearchStringFromDec.isEmpty()) { if (firstAppended) { sb.append(" OR "); } else { firstAppended = true; } sb.append("a.serialNumber LIKE :serialNumberDec"); } if (!serialNumberSearchStringFromHex.isEmpty()) { if (firstAppended) { sb.append(" OR "); } sb.append("a.serialNumber LIKE :serialNumberHex"); } sb.append(")"); } // NOTE: notBefore is not indexed.. we might want to disallow such search. if (request.isIssuedAfterUsed()) { sb.append(" AND (a.notBefore > :issuedAfter)"); } if (request.isIssuedBeforeUsed()) { sb.append(" AND (a.notBefore < :issuedBefore)"); } if (request.isExpiresAfterUsed()) { sb.append(" AND (a.expireDate > :expiresAfter)"); } if (request.isExpiresBeforeUsed()) { sb.append(" AND (a.expireDate < :expiresBefore)"); } // NOTE: revocationDate is not indexed.. we might want to disallow such search. if (request.isRevokedAfterUsed()) { sb.append(" AND (a.revocationDate > :revokedAfter)"); } if (request.isRevokedBeforeUsed()) { sb.append(" AND (a.revocationDate < :revokedBefore)"); } if (!request.getStatuses().isEmpty()) { sb.append(" AND (a.status IN (:status))"); if ((request.getStatuses().contains(CertificateConstants.CERT_REVOKED) || request.getStatuses().contains(CertificateConstants.CERT_ARCHIVED)) && !request.getRevocationReasons().isEmpty()) { sb.append(" AND (a.revocationReason IN (:revocationReason))"); } } // Don't constrain results to certain certificate profiles if root access is available and "any" CP is requested if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) { sb.append(" AND (a.certificateProfileId IN (:certificateProfileId))"); } // Don't constrain results to certain end entity profiles if root access is available and "any" EEP is requested if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) { sb.append(" AND (a.endEntityProfileId IN (:endEntityProfileId))"); } final Query query = entityManager.createQuery(sb.toString()); query.setParameter("issuerDN", issuerDns); if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) { query.setParameter("certificateProfileId", authorizedCpIds); } if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) { query.setParameter("endEntityProfileId", authorizedEepIds); } if (log.isDebugEnabled()) { log.debug(" issuerDN: " + Arrays.toString(issuerDns.toArray())); if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) { log.debug(" certificateProfileId: " + Arrays.toString(authorizedCpIds.toArray())); } else { log.debug(" certificateProfileId: Any (even deleted) profile(s) due to root access."); } if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) { log.debug(" endEntityProfileId: " + Arrays.toString(authorizedEepIds.toArray())); } else { log.debug(" endEntityProfileId: Any (even deleted) profile(s) due to root access."); } } if (!subjectDnSearchString.isEmpty()) { if (request.isSubjectDnSearchExact()) { query.setParameter("subjectDN", subjectDnSearchString); } else { query.setParameter("subjectDN", "%" + subjectDnSearchString + "%"); } } if (!subjectAnSearchString.isEmpty()) { if (request.isSubjectAnSearchExact()) { query.setParameter("subjectAltName", subjectAnSearchString); } else { query.setParameter("subjectAltName", "%" + subjectAnSearchString + "%"); } } if (!usernameSearchString.isEmpty()) { if (request.isUsernameSearchExact()) { query.setParameter("username", usernameSearchString); } else { query.setParameter("username", "%" + usernameSearchString + "%"); } } if (!serialNumberSearchStringFromDec.isEmpty()) { query.setParameter("serialNumberDec", serialNumberSearchStringFromDec); if (log.isDebugEnabled()) { log.debug(" serialNumberDec: " + serialNumberSearchStringFromDec); } } if (!serialNumberSearchStringFromHex.isEmpty()) { query.setParameter("serialNumberHex", serialNumberSearchStringFromHex); if (log.isDebugEnabled()) { log.debug(" serialNumberHex: " + serialNumberSearchStringFromHex); } } if (request.isIssuedAfterUsed()) { query.setParameter("issuedAfter", request.getIssuedAfter()); } if (request.isIssuedBeforeUsed()) { query.setParameter("issuedBefore", request.getIssuedBefore()); } if (request.isExpiresAfterUsed()) { query.setParameter("expiresAfter", request.getExpiresAfter()); } if (request.isExpiresBeforeUsed()) { query.setParameter("expiresBefore", request.getExpiresBefore()); } if (request.isRevokedAfterUsed()) { query.setParameter("revokedAfter", request.getRevokedAfter()); } if (request.isRevokedBeforeUsed()) { query.setParameter("revokedBefore", request.getRevokedBefore()); } if (!request.getStatuses().isEmpty()) { query.setParameter("status", request.getStatuses()); if ((request.getStatuses().contains(CertificateConstants.CERT_REVOKED) || request.getStatuses().contains(CertificateConstants.CERT_ARCHIVED)) && !request.getRevocationReasons().isEmpty()) { query.setParameter("revocationReason", request.getRevocationReasons()); } } final int maxResults = Math.min(getGlobalCesecoreConfiguration().getMaximumQueryCount(), request.getMaxResults()); query.setMaxResults(maxResults); /* Try to use the non-portable hint (depends on DB and JDBC driver) to specify how long in milliseconds the query may run. Possible behaviors: * - The hint is ignored * - A QueryTimeoutException is thrown * - A PersistenceException is thrown (and the transaction which don't have here is marked for roll-back) */ final long queryTimeout = getGlobalCesecoreConfiguration().getMaximumQueryTimeout(); if (queryTimeout > 0L) { query.setHint("javax.persistence.query.timeout", String.valueOf(queryTimeout)); } final List<String> fingerprints; try { fingerprints = query.getResultList(); for (final String fingerprint : fingerprints) { response.getCdws().add(certificateStoreSession.getCertificateData(fingerprint)); } response.setMightHaveMoreResults(fingerprints.size() == maxResults); if (log.isDebugEnabled()) { log.debug("Certificate search query: " + sb.toString() + " LIMIT " + maxResults + " \u2192 " + fingerprints.size() + " results. queryTimeout=" + queryTimeout + "ms"); } } catch (QueryTimeoutException e) { // Query.toString() does not return the SQL query executed just a java object hash. If Hibernate is being used we can get it using: // query.unwrap(org.hibernate.Query.class).getQueryString() // We don't have access to hibernate when building this class though, all querying should be moved to the ejbca-entity package. // See ECA-5341 String queryString = e.getQuery().toString(); // try { // queryString = e.getQuery().unwrap(org.hibernate.Query.class).getQueryString(); // } catch (PersistenceException pe) { // log.debug("Query.unwrap(org.hibernate.Query.class) is not supported by JPA provider"); // } log.info("Requested search query by " + authenticationToken + " took too long. Query was '" + queryString + "'. " + e.getMessage()); response.setMightHaveMoreResults(true); } catch (PersistenceException e) { log.info("Requested search query by " + authenticationToken + " failed, possibly due to timeout. " + e.getMessage()); response.setMightHaveMoreResults(true); } return response; }
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
/** * Verify that two Collections are deeply equivalent. Some of the Sets that * need to be verified do not implement a sensible equals method * (TreeMap.values for example).//from w w w .j a v a2 s . co m * * @param expected * @param actual */ private static <T> void _assertEquals(Collection<T> expected, Collection<T> actual) { // verify equivalence using collection interface assertEquals(expected.isEmpty(), actual.isEmpty()); assertEquals(expected.size(), actual.size()); assertTrue(expected.containsAll(actual)); assertTrue(actual.containsAll(expected)); for (T expectedValue : expected) { assertTrue(actual.contains(expectedValue)); } for (T actualValue : actual) { assertTrue(expected.contains(actualValue)); } }
From source file:nl.mpi.lamus.workspace.upload.implementation.LamusWorkspaceUploaderTest.java
@Test public void processTwoUploadedFiles_LinkingFailed() throws IOException, WorkspaceNodeNotFoundException, URISyntaxException, WorkspaceException, NodeNotFoundException, TypeCheckerException { final URI workspaceTopNodeArchiveURI = URI .create(handleProxyPlusPrefixWithSlash + UUID.randomUUID().toString()); final File workspaceTopNodeArchiveFile = new File("/archive/some/node.cmdi"); final String filename1 = "someFile.txt"; final File uploadedFile1 = new File(workspaceUploadDirectory, filename1); final URI uploadedFileURI1 = uploadedFile1.toURI(); final URL uploadedFileURL1 = uploadedFileURI1.toURL(); final WorkspaceNodeType fileNodeType1 = WorkspaceNodeType.RESOURCE_WRITTEN; final String fileMimetype1 = "text/plain"; final String filename2 = "someOtherFile.jpg"; final File uploadedFile2 = new File(workspaceUploadDirectory, filename2); final URI uploadedFileURI2 = uploadedFile2.toURI(); final URL uploadedFileURL2 = uploadedFileURI2.toURL(); final WorkspaceNodeType fileNodeType2 = WorkspaceNodeType.RESOURCE_IMAGE; final String fileMimetype2 = "image/jpeg"; final WorkspaceNode uploadedNode1 = new LamusWorkspaceNode(workspaceID, null, null); uploadedNode1.setName(filename1);// ww w . jav a 2s. c o m uploadedNode1.setStatus(WorkspaceNodeStatus.UPLOADED); uploadedNode1.setType(fileNodeType1); uploadedNode1.setFormat(fileMimetype1); uploadedNode1.setWorkspaceURL(uploadedFileURL1); final WorkspaceNode uploadedNode2 = new LamusWorkspaceNode(workspaceID, null, null); uploadedNode2.setName(filename2); uploadedNode2.setStatus(WorkspaceNodeStatus.UPLOADED); uploadedNode2.setType(fileNodeType2); uploadedNode2.setFormat(fileMimetype2); uploadedNode2.setWorkspaceURL(uploadedFileURL2); final Collection<File> uploadedFiles = new ArrayList<>(); uploadedFiles.add(mockFile1); uploadedFiles.add(mockFile2); final Collection<WorkspaceNode> uploadedNodes = new ArrayList<>(); uploadedNodes.add(uploadedNode1); uploadedNodes.add(uploadedNode2); //two files in the collection, so two loop cycles final Collection<ImportProblem> failedLinks = new ArrayList<>(); failedLinks.add(mockUploadProblem); context.checking(new Expectations() { { oneOf(mockWorkspaceDao).getWorkspace(workspaceID); will(returnValue(mockWorkspace)); oneOf(mockWorkspaceDao).getWorkspaceTopNode(workspaceID); will(returnValue(mockWorkspaceTopNode)); oneOf(mockWorkspaceTopNode).getArchiveURI(); will(returnValue(workspaceTopNodeArchiveURI)); oneOf(mockNodeDataRetriever).getNodeLocalFile(workspaceTopNodeArchiveURI); will(returnValue(workspaceTopNodeArchiveFile)); //first loop cycle oneOf(mockFile1).toURI(); will(returnValue(uploadedFileURI1)); oneOf(mockFile1).getName(); will(returnValue(filename1)); oneOf(mockNodeDataRetriever).triggerResourceFileCheck(uploadedFileURL1, filename1); will(returnValue(mockTypecheckedResults)); oneOf(mockNodeDataRetriever).isCheckedResourceArchivable(with(same(mockTypecheckedResults)), with(same(workspaceTopNodeArchiveFile)), with(any(StringBuilder.class))); will(returnValue(Boolean.TRUE)); oneOf(mockFile1).getName(); will(returnValue(filename1)); oneOf(mockTypecheckedResults).getCheckedMimetype(); will(returnValue(fileMimetype1)); oneOf(mockNodeUtil).convertMimetype(fileMimetype1); will(returnValue(fileNodeType1)); oneOf(mockArchiveFileLocationProvider).isFileInOrphansDirectory(mockFile1); will(returnValue(Boolean.FALSE)); oneOf(mockWorkspaceNodeFactory).getNewWorkspaceNodeFromFile(workspaceID, null, null, uploadedFileURL1, null, null, fileMimetype1, fileNodeType1, WorkspaceNodeStatus.UPLOADED, Boolean.FALSE); will(returnValue(uploadedNode1)); oneOf(mockWorkspaceDao).addWorkspaceNode(uploadedNode1); //second loop cycle oneOf(mockFile2).toURI(); will(returnValue(uploadedFileURI2)); oneOf(mockFile2).getName(); will(returnValue(filename2)); oneOf(mockNodeDataRetriever).triggerResourceFileCheck(uploadedFileURL2, filename2); will(returnValue(mockTypecheckedResults)); oneOf(mockNodeDataRetriever).isCheckedResourceArchivable(with(same(mockTypecheckedResults)), with(same(workspaceTopNodeArchiveFile)), with(any(StringBuilder.class))); will(returnValue(Boolean.TRUE)); oneOf(mockFile2).getName(); will(returnValue(filename2)); oneOf(mockTypecheckedResults).getCheckedMimetype(); will(returnValue(fileMimetype2)); oneOf(mockNodeUtil).convertMimetype(fileMimetype2); will(returnValue(fileNodeType2)); oneOf(mockArchiveFileLocationProvider).isFileInOrphansDirectory(mockFile2); will(returnValue(Boolean.FALSE)); oneOf(mockWorkspaceNodeFactory).getNewWorkspaceNodeFromFile(workspaceID, null, null, uploadedFileURL2, null, null, fileMimetype2, fileNodeType2, WorkspaceNodeStatus.UPLOADED, Boolean.FALSE); will(returnValue(uploadedNode2)); oneOf(mockWorkspaceDao).addWorkspaceNode(uploadedNode2); //check links oneOf(mockWorkspaceUploadHelper).assureLinksInWorkspace(mockWorkspace, uploadedNodes); will(returnValue(failedLinks)); } }); Collection<ImportProblem> result = uploader.processUploadedFiles(workspaceID, uploadedFiles); assertNotNull("Collection with failed uploads should not be null", result); assertFalse("Collection with failed uploads should not be empty", result.isEmpty()); assertTrue("Collection with failed uploads different from expected", result.containsAll(failedLinks)); }
From source file:org.apache.jackrabbit.spi2dav.RepositoryServiceImpl.java
/** * @see RepositoryService#isGranted(SessionInfo, ItemId, String[] actions) *///from www .j ava 2 s . c om public boolean isGranted(SessionInfo sessionInfo, ItemId itemId, String[] actions) throws RepositoryException { ReportMethod method = null; try { String uri = getItemUri(itemId, sessionInfo); ReportInfo reportInfo = new ReportInfo(JcrPrivilegeReport.PRIVILEGES_REPORT); reportInfo.setContentElement(DomUtil.hrefToXml(uri, domFactory)); method = new ReportMethod(uriResolver.getWorkspaceUri(sessionInfo.getWorkspaceName()), reportInfo); getClient(sessionInfo).executeMethod(method); method.checkSuccess(); MultiStatusResponse[] responses = method.getResponseBodyAsMultiStatus().getResponses(); if (responses.length < 1) { throw new ItemNotFoundException( "Unable to retrieve permissions for item " + saveGetIdString(itemId, sessionInfo)); } DavProperty p = responses[0].getProperties(DavServletResponse.SC_OK) .get(SecurityConstants.CURRENT_USER_PRIVILEGE_SET); if (p == null) { return false; } // build set of privileges from given actions. NOTE: since the actions // have no qualifying namespace, the {@link ItemResourceConstants#NAMESPACE} // is used. Set requiredPrivileges = new HashSet(); for (int i = 0; i < actions.length; i++) { requiredPrivileges.add(Privilege.getPrivilege(actions[i], ItemResourceConstants.NAMESPACE)); } // build set of privileges granted to the current user. CurrentUserPrivilegeSetProperty privSet = new CurrentUserPrivilegeSetProperty(p); Collection privileges = (Collection) privSet.getValue(); // check privileges present against required privileges. return privileges.containsAll(requiredPrivileges); } catch (IOException e) { throw new RepositoryException(e); } catch (DavException e) { throw ExceptionConverter.generate(e); } finally { if (method != null) { method.releaseConnection(); } } }