List of usage examples for java.util ArrayList iterator
public Iterator<E> iterator()
From source file:edu.cornell.mannlib.vitro.webapp.controller.grefine.JSONReconcileServlet.java
protected SearchQuery getQuery(String queryStr, String searchType, int limit, ArrayList<String[]> propertiesList) { if (queryStr == null) { log.error("There was no parameter '" + PARAM_QUERY + "' in the request."); return null; } else if (queryStr.length() > MAX_QUERY_LENGTH) { log.debug("The search was too long. The maximum " + "query length is " + MAX_QUERY_LENGTH); return null; }//from ww w . java 2 s .c o m /// original ///SearchQuery query = new SearchQuery(); /// test SearchQuery query = ApplicationUtils.instance().getSearchEngine().createQuery(queryStr.toLowerCase()); // original code: // query.setStart(0).setRows(DEFAULT_MAX_HIT_COUNT); // Google Refine specific: query.setStart(0).setRows(limit); // TODO: works better without using tokenizeNameQuery(), need to investigate a bit more /// comment out original: query.setQuery(queryStr); // Filter by type // e.g. http://xmlns.com/foaf/0.1/Person if (searchType != null) { query.addFilterQuery(VitroSearchTermNames.RDFTYPE + ":\"" + searchType + "\""); } // Added score to original code: query.addFields(VitroSearchTermNames.NAME_RAW, VitroSearchTermNames.URI, "*", "score"); // fields to retrieve // if propertiesList has elements, add extra queries to query Iterator<String[]> it = propertiesList.iterator(); while (it.hasNext()) { String[] pvPair = it.next(); query.addFilterQueries(tokenizeNameQuery(pvPair[1]), VitroSearchTermNames.RDFTYPE + ":\"" + pvPair[0] + "\""); } // Can't sort on multivalued field, so we sort the results in Java when we get them. // query.addSortField(VitroSearchTermNames.NAME_LOWERCASE, Order.ASC); return query; }
From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java
/** * THIS SHOULD RETURN HASHSET and not jsut Set because we add to it later (so it can't be Collections.emptySet()) * /*w w w .ja v a 2s . com*/ * @param theLastUpdated */ public static HashSet<Long> loadReverseIncludes(FhirContext theContext, EntityManager theEntityManager, Collection<Long> theMatches, Set<Include> theRevIncludes, boolean theReverseMode, DateRangeParam theLastUpdated) { if (theMatches.size() == 0) { return new HashSet<Long>(); } if (theRevIncludes == null || theRevIncludes.isEmpty()) { return new HashSet<Long>(); } String searchFieldName = theReverseMode ? "myTargetResourcePid" : "mySourceResourcePid"; Collection<Long> nextRoundMatches = theMatches; HashSet<Long> allAdded = new HashSet<Long>(); HashSet<Long> original = new HashSet<Long>(theMatches); ArrayList<Include> includes = new ArrayList<Include>(theRevIncludes); int roundCounts = 0; StopWatch w = new StopWatch(); boolean addedSomeThisRound; do { roundCounts++; HashSet<Long> pidsToInclude = new HashSet<Long>(); Set<Long> nextRoundOmit = new HashSet<Long>(); for (Iterator<Include> iter = includes.iterator(); iter.hasNext();) { Include nextInclude = iter.next(); if (nextInclude.isRecurse() == false) { iter.remove(); } boolean matchAll = "*".equals(nextInclude.getValue()); if (matchAll) { String sql; sql = "SELECT r FROM ResourceLink r WHERE r." + searchFieldName + " IN (:target_pids)"; TypedQuery<ResourceLink> q = theEntityManager.createQuery(sql, ResourceLink.class); q.setParameter("target_pids", nextRoundMatches); List<ResourceLink> results = q.getResultList(); for (ResourceLink resourceLink : results) { if (theReverseMode) { // if (theEverythingModeEnum.isEncounter()) { // if (resourceLink.getSourcePath().equals("Encounter.subject") || // resourceLink.getSourcePath().equals("Encounter.patient")) { // nextRoundOmit.add(resourceLink.getSourceResourcePid()); // } // } pidsToInclude.add(resourceLink.getSourceResourcePid()); } else { pidsToInclude.add(resourceLink.getTargetResourcePid()); } } } else { List<String> paths; RuntimeSearchParam param = null; if (theContext.getVersion().getVersion() == FhirVersionEnum.DSTU1) { paths = Collections.singletonList(nextInclude.getValue()); } else { String resType = nextInclude.getParamType(); if (isBlank(resType)) { continue; } RuntimeResourceDefinition def = theContext.getResourceDefinition(resType); if (def == null) { ourLog.warn("Unknown resource type in include/revinclude=" + nextInclude.getValue()); continue; } String paramName = nextInclude.getParamName(); param = isNotBlank(paramName) ? def.getSearchParam(paramName) : null; if (param == null) { ourLog.warn("Unknown param name in include/revinclude=" + nextInclude.getValue()); continue; } paths = param.getPathsSplit(); } String targetResourceType = defaultString(nextInclude.getParamTargetType(), null); for (String nextPath : paths) { String sql; boolean haveTargetTypesDefinedByParam = param != null && param.getTargets() != null && param.getTargets().isEmpty() == false; if (targetResourceType != null) { sql = "SELECT r FROM ResourceLink r WHERE r.mySourcePath = :src_path AND r." + searchFieldName + " IN (:target_pids) AND r.myTargetResourceType = :target_resource_type"; } else if (haveTargetTypesDefinedByParam) { sql = "SELECT r FROM ResourceLink r WHERE r.mySourcePath = :src_path AND r." + searchFieldName + " IN (:target_pids) AND r.myTargetResourceType in (:target_resource_types)"; } else { sql = "SELECT r FROM ResourceLink r WHERE r.mySourcePath = :src_path AND r." + searchFieldName + " IN (:target_pids)"; } TypedQuery<ResourceLink> q = theEntityManager.createQuery(sql, ResourceLink.class); q.setParameter("src_path", nextPath); q.setParameter("target_pids", nextRoundMatches); if (targetResourceType != null) { q.setParameter("target_resource_type", targetResourceType); } else if (haveTargetTypesDefinedByParam) { q.setParameter("target_resource_types", param.getTargets()); } List<ResourceLink> results = q.getResultList(); for (ResourceLink resourceLink : results) { if (theReverseMode) { Long pid = resourceLink.getSourceResourcePid(); pidsToInclude.add(pid); } else { Long pid = resourceLink.getTargetResourcePid(); pidsToInclude.add(pid); } } } } } if (theLastUpdated != null && (theLastUpdated.getLowerBoundAsInstant() != null || theLastUpdated.getUpperBoundAsInstant() != null)) { pidsToInclude = new HashSet<Long>( filterResourceIdsByLastUpdated(theEntityManager, theLastUpdated, pidsToInclude)); } for (Long next : pidsToInclude) { if (original.contains(next) == false && allAdded.contains(next) == false) { theMatches.add(next); } } pidsToInclude.removeAll(nextRoundOmit); addedSomeThisRound = allAdded.addAll(pidsToInclude); nextRoundMatches = pidsToInclude; } while (includes.size() > 0 && nextRoundMatches.size() > 0 && addedSomeThisRound); ourLog.info("Loaded {} {} in {} rounds and {} ms", new Object[] { allAdded.size(), theReverseMode ? "_revincludes" : "_includes", roundCounts, w.getMillisAndRestart() }); return allAdded; }
From source file:com.planetmayo.debrief.satc_rcp.views.MaintainContributionsView.java
protected void redoOwnshipStates() { if (legPlot == null) return;/*from w w w . j a v a 2 s.co m*/ boolean showCourses = true; if (showOSCourse != null) showCourses = showOSCourse.getSelection(); java.awt.Color courseCol = java.awt.Color.blue.darker().darker(); java.awt.Color speedCol = java.awt.Color.blue.brighter().brighter(); // ok, now loop through and set them long startTime = Long.MAX_VALUE; long endTime = Long.MIN_VALUE; // clear any datasets legPlot.setDataset(0, null); legPlot.setDataset(1, null); // hmm, actually we have to remove any target leg markers @SuppressWarnings("unchecked") Collection<IntervalMarker> markers = legPlot.getDomainMarkers(Layer.BACKGROUND); if (markers != null) { ArrayList<IntervalMarker> markersToDelete = new ArrayList<IntervalMarker>(markers); Iterator<IntervalMarker> mIter = markersToDelete.iterator(); while (mIter.hasNext()) { IntervalMarker im = mIter.next(); legPlot.removeDomainMarker(im); } } // hey, does it have any ownship legs? TimeSeriesCollection tscC = new TimeSeriesCollection(); TimeSeriesCollection tscS = new TimeSeriesCollection(); TimeSeriesCollection tscCLegs = new TimeSeriesCollection(); TimeSeriesCollection tscSLegs = new TimeSeriesCollection(); TimeSeries courses = new TimeSeries("Course"); TimeSeries bearings = new TimeSeries("Bearings"); TimeSeries speeds = new TimeSeries("Speed"); TimeSeries courseLegs = new TimeSeries("Course (leg)"); TimeSeries speedLegs = new TimeSeries("Speed (leg)"); Iterator<BaseContribution> conts = activeSolver.getContributions().iterator(); while (conts.hasNext()) { BaseContribution baseC = conts.next(); if (baseC.isActive()) if (baseC instanceof BearingMeasurementContribution) { BearingMeasurementContribution bmc = (BearingMeasurementContribution) baseC; Iterator<LegOfData> lIter = null; LegOfData thisLeg = null; if (bmc.getOwnshipLegs() != null) { lIter = bmc.getOwnshipLegs().iterator(); thisLeg = lIter.next(); } List<HostState> hostStates = bmc.getHostState(); if (hostStates != null) { Iterator<HostState> stateIter = hostStates.iterator(); while (stateIter.hasNext()) { BearingMeasurementContribution.HostState hostState = stateIter.next(); long thisTime = hostState.time; double thisCourse = hostState.courseDegs; if (showCourses) courses.add(new FixedMillisecond(thisTime), thisCourse); double thisSpeed = hostState.speedKts; speeds.add(new FixedMillisecond(thisTime), thisSpeed); startTime = Math.min(thisTime, startTime); endTime = Math.max(thisTime, endTime); // sort out if this is in a leg or not if (thisLeg != null) { if (thisTime > thisLeg.getEnd() && lIter.hasNext()) { thisLeg = lIter.next(); } else { if (thisTime >= thisLeg.getStart()) { speedLegs.add(new FixedMillisecond(thisTime), thisSpeed); if (showCourses) courseLegs.add(new FixedMillisecond(thisTime), thisCourse); } } } } } // also, we wish to show the bearings from the BMC Iterator<BMeasurement> cuts = bmc.getMeasurements().iterator(); while (cuts.hasNext()) { BearingMeasurementContribution.BMeasurement measurement = cuts.next(); if (measurement.isActive()) { long thisT = measurement.getDate().getTime(); bearings.add(new FixedMillisecond(thisT), Math.toDegrees(Math.abs(measurement.getBearingRads()))); } } } } // HEY, also shade the ownship legs conts = activeSolver.getContributions().iterator(); while (conts.hasNext()) { BaseContribution baseC = conts.next(); if (baseC.isActive()) { if (baseC instanceof BearingMeasurementContribution) { BearingMeasurementContribution bmc = (BearingMeasurementContribution) baseC; Iterator<LegOfData> lIter = null; if (bmc.getOwnshipLegs() != null) { int ctr = 1; lIter = bmc.getOwnshipLegs().iterator(); while (lIter.hasNext()) { LegOfData thisL = lIter.next(); long thisStart = thisL.getStart(); long thisFinish = thisL.getEnd(); java.awt.Color transCol = new java.awt.Color(0, 0, 255, 12); final Marker bst = new IntervalMarker(thisStart, thisFinish, transCol, new BasicStroke(2.0f), null, null, 1.0f); bst.setLabel("O/S-" + ctr++); bst.setLabelAnchor(RectangleAnchor.TOP_LEFT); bst.setLabelFont(new Font("SansSerif", Font.ITALIC + Font.BOLD, 10)); bst.setLabelTextAnchor(TextAnchor.TOP_LEFT); legPlot.addDomainMarker(bst, Layer.BACKGROUND); } } } } } tscS.addSeries(speeds); tscSLegs.addSeries(speedLegs); tscC.addSeries(bearings); if (showCourses) { tscC.addSeries(courses); tscCLegs.addSeries(courseLegs); } legPlot.setDataset(0, null); legPlot.setDataset(1, null); legPlot.setDataset(2, null); legPlot.setDataset(3, null); legPlot.setDataset(0, tscC); legPlot.setDataset(1, tscS); legPlot.setDataset(2, tscCLegs); legPlot.setDataset(3, tscSLegs); final NumberAxis axis2 = new NumberAxis("Speed (Kts)"); legPlot.setRangeAxis(1, axis2); legPlot.mapDatasetToRangeAxis(1, 1); legPlot.mapDatasetToRangeAxis(3, 1); legPlot.getRangeAxis(0).setLabel("Crse/Brg (Degs)"); legPlot.mapDatasetToRangeAxis(0, 0); legPlot.mapDatasetToRangeAxis(2, 0); final XYLineAndShapeRenderer lineRenderer1 = new XYLineAndShapeRenderer(true, true); lineRenderer1.setSeriesPaint(1, courseCol); lineRenderer1.setSeriesShape(1, ShapeUtilities.createDiamond(0.1f)); lineRenderer1.setSeriesPaint(0, java.awt.Color.RED); lineRenderer1.setSeriesShape(0, ShapeUtilities.createDiamond(2f)); final XYLineAndShapeRenderer lineRenderer2 = new XYLineAndShapeRenderer(true, false); lineRenderer2.setSeriesPaint(0, speedCol); final XYLineAndShapeRenderer lineRenderer3 = new XYLineAndShapeRenderer(false, true); lineRenderer3.setSeriesPaint(0, courseCol); lineRenderer3.setSeriesShape(0, ShapeUtilities.createUpTriangle(2f)); final XYLineAndShapeRenderer lineRenderer4 = new XYLineAndShapeRenderer(false, true); lineRenderer4.setSeriesPaint(0, speedCol); lineRenderer4.setSeriesShape(0, ShapeUtilities.createDownTriangle(2f)); // ok, and store them legPlot.setRenderer(0, lineRenderer1); legPlot.setRenderer(1, lineRenderer2); legPlot.setRenderer(2, lineRenderer3); legPlot.setRenderer(3, lineRenderer4); if (startTime != Long.MAX_VALUE) legPlot.getDomainAxis().setRange(startTime, endTime); // ok - get the straight legs to sort themselves out // redoStraightLegs(); }
From source file:jdbc.pool.JDBCPoolTestCase.java
/** * Tests Inactive time out closing of the JDBC Connection. * // www . j av a 2s . c om * Check whether the connection returns back to the pool. */ public void testInactiveTimeout() { System.out.println("testInactiveTimeout Start."); CConnectionPoolManager manager = null; try { manager = create(); Connection conOra1 = manager.getConnection("ORACLE"); Connection realCon = null; Connection conOra2 = manager.getConnection("ORACLE"); if (conOra2 instanceof ConnectionWrapper) { ConnectionWrapper wrapper = (ConnectionWrapper) conOra2; realCon = wrapper.realConnection(); } else { fail("Connection returned is not an instance of ConnectionWrapper"); } conOra2.close(); try { // 4 = 1 + 3 + (1) As the maximum time in which the con will be // closed is 4 have an additional 1 minute extra Thread.sleep(5 * 60 * 1000); // Shrink Pool Interval 1 minute + Inactive timeout 3 mins. } catch (InterruptedException e1) { e1.printStackTrace(); } assertTrue("Real Connection is closed", realCon.isClosed()); conOra1.close(); CPoolStatisticsBean bean = manager.getPoolStatistics("ORACLE"); assertEquals("Pool Name", "ORACLE", bean.getPoolName()); System.out.println("********************************************************"); ArrayList al = manager.getPoolStatisticsHistory("ORACLE"); assertTrue("Statistics History Count", 5 >= al.size()); for (Iterator iter = al.iterator(); iter.hasNext();) { CPoolStatisticsBean element = (CPoolStatisticsBean) iter.next(); System.out.println(element.toString()); } System.out.println("********************************************************"); } catch (ConfigurationException e) { e.printStackTrace(); fail("Caught ConfigurationException"); } catch (ParseException e) { e.printStackTrace(); fail("Caught ParseException"); } catch (IOException e) { e.printStackTrace(); fail("Caught IOException"); } catch (SQLException e) { e.printStackTrace(); fail("Caught SQLException"); } catch (ClassNotFoundException e) { e.printStackTrace(); fail("Caught ClassNotFoundException"); } finally { manager.destroy(true); } System.out.println("testInactiveTimeout end."); }
From source file:com.termmed.reconciliation.RelationshipReconciliation.java
/** * Group reassignment.// w ww. j a v a 2s . co m * * @param snorelA the snorel a * @param snorelB the snorel b * @throws IOException Signals that an I/O exception has occurred. */ private void groupReassignment(ArrayList<Relationship> snorelA, ArrayList<Relationship> snorelB) throws IOException { int countChangedGroupNumber = 0; long startTime = System.currentTimeMillis(); StringBuilder s = new StringBuilder(); s.append("\r\n::: [Start group number reconciliation]"); Collections.sort(snorelA); Collections.sort(snorelB); Iterator<Relationship> itA = snorelA.iterator(); Iterator<Relationship> itB = snorelB.iterator(); Relationship rel_A = null; boolean done_A = false; if (itA.hasNext()) { rel_A = itA.next(); } else { done_A = true; } Relationship rel_B = null; boolean done_B = false; if (itB.hasNext()) { rel_B = itB.next(); } else { done_B = true; } // BY SORT ORDER, LOWER NUMBER ADVANCES FIRST while (!done_A && !done_B) { if (rel_A.sourceId == rel_B.sourceId) { long thisC1 = rel_A.sourceId; // REMAINDER LIST_A GROUP 0 FOR C1 while (rel_A.sourceId == thisC1 && rel_A.group == 0 && !done_A) { if (itA.hasNext()) { rel_A = itA.next(); } else { done_A = true; break; } } // REMAINDER LIST_B GROUP 0 FOR C1 while (rel_B.sourceId == thisC1 && rel_B.group == 0 && !done_B) { if (itB.hasNext()) { rel_B = itB.next(); } else { done_B = true; break; } } // ** SEGMENT GROUPS ** RelationshipGroupList groupList_A = new RelationshipGroupList(); RelationshipGroupList groupList_B = new RelationshipGroupList(); RelationshipGroup groupA = null; RelationshipGroup groupB = null; // SEGMENT GROUPS IN LIST_A int prevGroup = Integer.MIN_VALUE; while (rel_A.sourceId == thisC1 && !done_A) { if (rel_A.group != prevGroup) { groupA = new RelationshipGroup(); groupList_A.add(groupA); } groupA.add(rel_A); prevGroup = rel_A.group; if (itA.hasNext()) { rel_A = itA.next(); } else { done_A = true; } } // SEGMENT GROUPS IN LIST_B prevGroup = Integer.MIN_VALUE; while (rel_B.sourceId == thisC1 && !done_B) { if (rel_B.group != prevGroup) { groupB = new RelationshipGroup(); groupList_B.add(groupB); } groupB.add(rel_B); prevGroup = rel_B.group; if (itB.hasNext()) { rel_B = itB.next(); } else { done_B = true; } } int dist; HashMap<Integer, List<Integer[]>> mapGroups = new HashMap<Integer, List<Integer[]>>(); HashMap<Integer, List<Integer[]>> minDist = new HashMap<Integer, List<Integer[]>>(); Integer prevRGNum; Integer currRGNum; if (groupList_B.size() > 0) { for (Integer sgb = 0; sgb < groupList_B.size(); sgb++) { currRGNum = groupList_B.get(sgb).get(0).group; if (currRGNum != 0) { for (Integer sga = 0; sga < groupList_A.size(); sga++) { prevRGNum = groupList_A.get(sga).get(0).group; if (prevRGNum != 0) { dist = groupList_B.get(sgb) .getDistanceToGroupInSameConcept(groupList_A.get(sga)); List<Integer[]> tmplist; if (mapGroups.containsKey(currRGNum)) { tmplist = mapGroups.get(currRGNum); } else { tmplist = new ArrayList<Integer[]>(); } tmplist.add(new Integer[] { prevRGNum, dist }); mapGroups.put(currRGNum, tmplist); List<Integer[]> tmplist2; if (minDist.containsKey(prevRGNum)) { tmplist2 = minDist.get(prevRGNum); } else { tmplist2 = new ArrayList<Integer[]>(); } tmplist2.add(new Integer[] { currRGNum, dist }); minDist.put(prevRGNum, tmplist2); } } } } HashMap<Integer, Integer> endMap = new HashMap<Integer, Integer>(); if (mapGroups.size() > 0) { Integer bestPrevRGNum; Integer bestCurrRGNum; List<Integer> usageCurrGroups = new ArrayList<Integer>(); List<Integer> usagePrevGroups = new ArrayList<Integer>(); boolean incomplete = true; boolean tooMuchPrev = false; boolean tooMuchCurr = false; while (incomplete && !tooMuchPrev && !tooMuchCurr) { incomplete = false; for (Integer sgb = 0; sgb < groupList_B.size(); sgb++) { currRGNum = groupList_B.get(sgb).get(0).group; if (!usageCurrGroups.contains(currRGNum)) { incomplete = true; List<Integer[]> currDistances = mapGroups.get(currRGNum); bestPrevRGNum = getBestGroupNumber(currDistances, usagePrevGroups); if (bestPrevRGNum == null) { tooMuchCurr = true; break; } List<Integer[]> prevDistances = minDist.get(bestPrevRGNum); bestCurrRGNum = getBestGroupNumber(prevDistances, usageCurrGroups); if (bestCurrRGNum == null) { tooMuchPrev = true; break; } if (bestCurrRGNum == currRGNum) { endMap.put(currRGNum, bestPrevRGNum); usageCurrGroups.add(currRGNum); usagePrevGroups.add(bestPrevRGNum); } } } } } Integer nextNum; for (Integer sgb = 0; sgb < groupList_B.size(); sgb++) { currRGNum = groupList_B.get(sgb).get(0).group; if (!endMap.containsKey(currRGNum)) { nextNum = nextRoleGroupNumber(endMap); endMap.put(currRGNum, nextNum); } } for (RelationshipGroup relationshipGroup : groupList_B) { for (Relationship relationship : relationshipGroup) { if (relationship.group != endMap.get(relationship.group)) { countChangedGroupNumber++; relationship.group = endMap.get(relationship.group); } } } } } else if (rel_A.sourceId > rel_B.sourceId) { // CASE 2: LIST_B HAS CONCEPT NOT IN LIST_A long thisC1 = rel_B.sourceId; while (rel_B.sourceId == thisC1) { if (itB.hasNext()) { rel_B = itB.next(); } else { done_B = true; break; } } } else { // CASE 3: LIST_A HAS CONCEPT NOT IN LIST_B long thisC1 = rel_A.sourceId; while (rel_A.sourceId == thisC1) { if (itA.hasNext()) { rel_A = itA.next(); } else { done_A = true; break; } } } } s.append("\r\n::: Relationships with group number changes = \t" + countChangedGroupNumber); s.append("\r\n::: [Partial time] Sort/Compare Input & Output: \t" + toStringLapseSec(startTime) + "\t(mS)\t"); s.append("\r\n"); logger.info(s.toString()); }
From source file:it.cnr.icar.eric.server.security.authorization.AuthorizationServiceImpl.java
/** * Check if user is authorized to perform specified request using V3 * specification./*ww w . java2 s . co m*/ * <p> * Check if the specified User (requestor) is authorized to make this * request or not. The initial subject lists contains the object in the * request is a resource. The primary action is determined by the type of * request. In addition * * <ul> * <li> * <b><i>AdhocQueryRequest: </i></b> Process query as normal and then filter * out objects that should not be visible to the client.</li> * <li> * <b><i>ApproveObjectRequest: </i></b> Check if subject is authorized for * the approve action.</li> * <li> * <b><i>Deprecate/UndeprecateRequest: </i></b> Check if subject is * authorized for the deprecate/undeprecate action.</li> * <li> * <b><i>RemoveObjectRequest: </i></b> Check if subject is authorized for * the delete action.</li> * <li> * <b><i>SubmitObjectsRequest/UpdateObjectsRequest: </i></b> Check if * subject authorized for the create action. Check any referenced objects * and see if their policies allows reference action.</li> * </ul> * * @todo Do we need any new Attribute types by Extending AttributeValue * (have string URI etc.)?? * @todo Do we need any new functions?? * * @throws RegistryException */ @SuppressWarnings({ "static-access", "deprecation" }) public AuthorizationResult checkAuthorization(ServerRequestContext context) throws RegistryException { try { RegistryRequestType registryRequest = context.getCurrentRegistryRequest(); if (null == context.getUser()) { // Set context user as RegistryGuest built in context.setUser(ac.registryGuest); } String userId = context.getUser().getId(); AuthorizationResult authRes = new AuthorizationResult(userId); boolean isAdmin = context.isRegistryAdministrator(); if (isAdmin) { // Allow RegistryAdmin role all privileges return authRes; } Set<Subject> subjects = new HashSet<Subject>(); Set<Attribute> actions = new HashSet<Attribute>(); Set<Attribute> environment = new HashSet<Attribute>(); Attribute actionAttr = null; boolean readOnly = false; String action = bu.getActionFromRequest(registryRequest); actionAttr = new Attribute(new URI(ACTION_ATTRIBUTE_ID), new URI(StringAttribute.identifier), null, null, new StringAttribute(action)); // Determine the action attributes. if (registryRequest instanceof AdhocQueryRequest) { readOnly = true; } actions.add(actionAttr); // Init subject attributes HashSet<Attribute> userSubjectAttributes = new HashSet<Attribute>(); Attribute idSubjectAttr = new Attribute(new URI(SUBJECT_ATTRIBUTE_ID), new URI(AnyURIAttribute.identifier), null, null, new AnyURIAttribute(new URI(userId))); userSubjectAttributes.add(idSubjectAttr); Attribute userSubjectAttr = new Attribute(new URI(SUBJECT_ATTRIBUTE_USER), new URI(ObjectAttribute.identifier), null, null, new ObjectAttribute(context.getUser())); userSubjectAttributes.add(userSubjectAttr); Subject userSubject = new Subject(new URI(AttributeDesignator.SUBJECT_CATEGORY_DEFAULT), userSubjectAttributes); subjects.add(userSubject); // Pass RequestContext as an environment attribute Attribute requestEnvAttr = new Attribute(new URI(ENVIRONMENT_ATTRIBUTE_REQUEST_CONTEXT), new URI(ObjectAttribute.identifier), null, null, new ObjectAttribute(context)); environment.add(requestEnvAttr); // Iterate over each resource and see if action is authorized on the // resource by the subject ArrayList<String> ids = new ArrayList<String>(); if (registryRequest instanceof AdhocQueryRequest) { // For AdhocQueryRequest query is already done and result is in // queryResults. Now do access control check on queryResults. Iterator<?> iter = context.getQueryResults().iterator(); while (iter.hasNext()) { IdentifiableType ro = (IdentifiableType) iter.next(); ids.add(ro.getId()); } } else { ids.addAll(bu.getIdsFromRequest(registryRequest)); } // Optimization: Get ownersMap in a single query and cache it @SuppressWarnings("unused") HashMap<String, String> ownersMap = getOwnersMap(context, ids); Iterator<String> idsIter = ids.iterator(); while (idsIter.hasNext()) { String id = idsIter.next(); if (id != null) { if ((!readOnly) && (id.equals(idForDefaultACP))) { // Auth check for defaultACP is special and requires // that // it is submitted by RegistryAdministrator role. // Note this will be generalized when we have better // Role Based Access Control (RBAC) support if (!isAdmin) { String msg = getExceptionMessage( "message.error.authorization.allowedOnlyToAdmin.defineDefaultACP", id, context.getUser(), getActionString(actions)); throw new UnauthorizedRequestException(id, context.getUser().getId(), getActionString(actions), msg); } } else { try { checkAuthorizationForResource(context, id, subjects, actions, environment); authRes.addPermittedResource(id); } catch (UnauthorizedRequestException ure) { authRes.addDeniedResourceException(ure); } catch (RegistryException re) { if (re.getCause() instanceof UnauthorizedRequestException) { authRes.addDeniedResourceException((UnauthorizedRequestException) re.getCause()); } else { throw re; } } } } else { @SuppressWarnings("unused") int i = 0; } } log.debug("userId=" + userId + " is " + (authRes.getResult() == AuthorizationResult.PERMIT_NONE ? "not " : "") + "allowed to perform the requested operation."); return authRes; } catch (URISyntaxException e) { throw new RegistryException(e); } catch (AuthorizationException e) { throw e; } catch (JAXRException e) { throw new RegistryException(e); } }
From source file:de.unijena.bioinf.FragmentationTreeConstruction.computation.FragmentationPatternAnalysis.java
/** * Step 6: Decomposition//from w w w. j a v a2 s. c o m * Decompose each peak as well as the parent peak */ public ProcessedInput performDecomposition(ProcessedInput input) { final FormulaConstraints constraints = input.getMeasurementProfile().getFormulaConstraints(); final Ms2Experiment experiment = input.getExperimentInformation(); final Deviation parentDeviation = input.getMeasurementProfile().getAllowedMassDeviation(); // sort again... final ArrayList<ProcessedPeak> processedPeaks = new ArrayList<ProcessedPeak>(input.getMergedPeaks()); Collections.sort(processedPeaks, new ProcessedPeak.MassComparator()); final ProcessedPeak parentPeak = processedPeaks.get(processedPeaks.size() - 1); // decompose peaks final PeakAnnotation<DecompositionList> decompositionList = input .getOrCreatePeakAnnotation(DecompositionList.class); final MassToFormulaDecomposer decomposer = decomposers.getDecomposer(constraints.getChemicalAlphabet()); final Ionization ion = experiment.getPrecursorIonType().getIonization(); final Deviation fragmentDeviation = input.getMeasurementProfile().getAllowedMassDeviation(); final List<MolecularFormula> pmds = decomposer.decomposeToFormulas( experiment.getPrecursorIonType().subtractIonAndAdduct(parentPeak.getOriginalMz()), parentDeviation, constraints); // add adduct to molecular formula of the ion - because the adduct might get lost during fragmentation { final MolecularFormula adduct = experiment.getPrecursorIonType().getAdduct(); final ListIterator<MolecularFormula> iter = pmds.listIterator(); while (iter.hasNext()) { final MolecularFormula f = iter.next(); iter.set(f.add(adduct)); } } decompositionList.set(parentPeak, DecompositionList.fromFormulas(pmds)); int j = 0; for (ProcessedPeak peak : processedPeaks.subList(0, processedPeaks.size() - 1)) { peak.setIndex(j++); decompositionList.set(peak, DecompositionList.fromFormulas( decomposer.decomposeToFormulas(peak.getUnmodifiedMass(), fragmentDeviation, constraints))); } parentPeak.setIndex(processedPeaks.size() - 1); assert parentPeak == processedPeaks.get(processedPeaks.size() - 1); // important: for each two peaks which are within 2*massrange: // => make decomposition list disjoint final Deviation window = fragmentDeviation.multiply(2); for (int i = 1; i < processedPeaks.size() - 1; ++i) { if (window.inErrorWindow(processedPeaks.get(i).getMz(), processedPeaks.get(i - 1).getMz())) { final HashSet<MolecularFormula> right = new HashSet<MolecularFormula>( decompositionList.get(processedPeaks.get(i)).getFormulas()); final ArrayList<MolecularFormula> left = new ArrayList<MolecularFormula>( decompositionList.get(processedPeaks.get(i - 1)).getFormulas()); final double leftMass = ion.subtractFromMass(processedPeaks.get(i - 1).getMass()); final double rightMass = ion.subtractFromMass(processedPeaks.get(i).getMass()); final Iterator<MolecularFormula> leftIter = left.iterator(); while (leftIter.hasNext()) { final MolecularFormula leftFormula = leftIter.next(); if (right.contains(leftFormula)) { if (Math.abs(leftFormula.getMass() - leftMass) < Math .abs(leftFormula.getMass() - rightMass)) { right.remove(leftFormula); } else { leftIter.remove(); } } } decompositionList.set(processedPeaks.get(i - 1), DecompositionList.fromFormulas(left)); decompositionList.set(processedPeaks.get(i), DecompositionList.fromFormulas(right)); } } return postProcess(PostProcessor.Stage.AFTER_DECOMPOSING, input); }
From source file:jdbc.pool.JDBCPoolOracleConnectionTest.java
/** * Tests Inactive time out closing of the JDBC Connection. * //from w ww . j a va 2 s . c o m * Check whether the connection returns back to the pool. */ public void testInactiveTimeout() { System.out.println("testInactiveTimeout Start."); testGetInstanceNull(); CConnectionPoolManager manager = null; try { manager = create(); Connection conOra1 = manager.getConnection("ORACLE"); Connection realCon = null; Connection conOra2 = manager.getConnection("ORACLE"); if (conOra2 instanceof ConnectionWrapper) { ConnectionWrapper wrapper = (ConnectionWrapper) conOra2; realCon = wrapper.realConnection(); } else { fail("Connection returned is not an instance of ConnectionWrapper"); } conOra2.close(); try { // 4 = 1 + 3 + (1) As the maximum time in which the con will be // closed is 4 have an additional 1 minute extra Thread.sleep(5 * 60 * 1000); // Shrink Pool Interval 1 minute + Inactive timeout 3 mins. } catch (InterruptedException e1) { e1.printStackTrace(); } assertTrue("Real Connection is closed", realCon.isClosed()); conOra1.close(); CPoolStatisticsBean bean = manager.getPoolStatistics("ORACLE"); assertEquals("Pool Name", "ORACLE", bean.getPoolName()); System.out.println("********************************************************"); ArrayList al = manager.getPoolStatisticsHistory("ORACLE"); assertTrue("Statistics History Count", 5 >= al.size()); for (Iterator iter = al.iterator(); iter.hasNext();) { CPoolStatisticsBean element = (CPoolStatisticsBean) iter.next(); System.out.println(element.toString()); } System.out.println("********************************************************"); } catch (ConfigurationException e) { e.printStackTrace(); fail("Caught ConfigurationException"); } catch (ParseException e) { e.printStackTrace(); fail("Caught ParseException"); } catch (IOException e) { e.printStackTrace(); fail("Caught IOException"); } catch (SQLException e) { e.printStackTrace(); fail("Caught SQLException"); } catch (ClassNotFoundException e) { e.printStackTrace(); fail("Caught ClassNotFoundException"); } finally { manager.destroy(true); } System.out.println("testInactiveTimeout end."); }
From source file:org.archive.crawler.frontier.WorkQueueFrontier.java
/** Compact report of all nonempty queues (one queue per line) * //from w ww . j a v a2s.c o m * @param writer */ public void allNonemptyReportTo(PrintWriter writer) { ArrayList<WorkQueue> inProcessQueuesCopy; synchronized (this.inProcessQueues) { // grab a copy that will be stable against mods for report duration Collection<WorkQueue> inProcess = this.inProcessQueues; inProcessQueuesCopy = new ArrayList<WorkQueue>(inProcess); } writer.print("\n -----===== IN-PROCESS QUEUES =====-----\n"); queueSingleLinesTo(writer, inProcessQueuesCopy.iterator()); writer.print("\n -----===== READY QUEUES =====-----\n"); queueSingleLinesTo(writer, this.readyClassQueues.iterator()); writer.print("\n -----===== SNOOZED QUEUES =====-----\n"); queueSingleLinesTo(writer, this.snoozedClassQueues.iterator()); queueSingleLinesTo(writer, this.snoozedOverflow.values().iterator()); writer.print("\n -----===== INACTIVE QUEUES =====-----\n"); for (Queue<String> inactiveQueues : getInactiveQueuesByPrecedence().values()) { queueSingleLinesTo(writer, inactiveQueues.iterator()); } writer.print("\n -----===== RETIRED QUEUES =====-----\n"); queueSingleLinesTo(writer, getRetiredQueues().iterator()); }
From source file:com.microsoft.tfs.core.httpclient.MultiThreadedHttpConnectionManager.java
/** * Closes and releases all connections currently checked out of the given * connection pool.//from www. j a va 2 s. c om * * @param connectionPool * the connection pool to shutdown the connections for */ private static void shutdownCheckedOutConnections(final ConnectionPool connectionPool) { log.debug("shutdownCheckedOutConnections: waiting for synchronization."); // keep a list of the connections to be closed final ArrayList connectionsToClose = new ArrayList(); synchronized (REFERENCE_TO_CONNECTION_SOURCE) { log.debug("shutdownCheckedOutConnections: collecting coonection list."); final Iterator referenceIter = REFERENCE_TO_CONNECTION_SOURCE.keySet().iterator(); while (referenceIter.hasNext()) { final Reference ref = (Reference) referenceIter.next(); final ConnectionSource source = (ConnectionSource) REFERENCE_TO_CONNECTION_SOURCE.get(ref); if (source.connectionPool == connectionPool) { referenceIter.remove(); final HttpConnection connection = (HttpConnection) ref.get(); if (connection != null) { connectionsToClose.add(connection); } } } } log.debug("shutdownCheckedOutConnections: connections to close count = " + connectionsToClose.size()); // close and release the connections outside of the synchronized block // to // avoid holding the lock for too long for (final Iterator i = connectionsToClose.iterator(); i.hasNext();) { final HttpConnection connection = (HttpConnection) i.next(); connection.close(); // remove the reference to the connection manager. this ensures // that the we don't accidentally end up here again connection.setHttpConnectionManager(null); connection.releaseConnection(); } }