List of usage examples for java.util Set clear
void clear();
From source file:org.apache.vxquery.compiler.rewriter.rules.PushAggregateIntoGroupbyRule.java
private boolean collectVarsBottomUp(Mutable<ILogicalOperator> opRef, IOptimizationContext context, Map<LogicalVariable, Integer> gbyListifyVarsCount, Map<LogicalVariable, GroupByOperator> gbyWithAgg, Map<LogicalVariable, Integer> gbyAggVarToPlanIndex, Map<ILogicalExpression, ILogicalExpression> aggregateExprToVarExpr) throws AlgebricksException { AbstractLogicalOperator op1 = (AbstractLogicalOperator) opRef.getValue(); context.addToDontApplySet(this, op1); boolean change = false; for (Mutable<ILogicalOperator> child : op1.getInputs()) { if (collectVarsBottomUp(child, context, gbyListifyVarsCount, gbyWithAgg, gbyAggVarToPlanIndex, aggregateExprToVarExpr)) { change = true;//from ww w . j a va2s .c o m } } Set<LogicalVariable> used = new HashSet<>(); VariableUtilities.getUsedVariables(op1, used); switch (op1.getOperatorTag()) { case ASSIGN: case SELECT: { boolean found = false; // Do some prefiltering: check if the Assign uses any gby vars. for (LogicalVariable v : used) { if (gbyListifyVarsCount.get(v) != null) { found = true; break; } } if (found) { if (op1.getOperatorTag() == LogicalOperatorTag.ASSIGN) { AssignOperator assign = (AssignOperator) op1; for (Mutable<ILogicalExpression> exprRef : assign.getExpressions()) { Pair<Boolean, ILogicalExpression> p = extractAggFunctionsFromExpression(exprRef, gbyWithAgg, aggregateExprToVarExpr, context); if (p.first) { change = true; exprRef.setValue(p.second); } } } if (op1.getOperatorTag() == LogicalOperatorTag.SELECT) { SelectOperator select = (SelectOperator) op1; Mutable<ILogicalExpression> exprRef = select.getCondition(); Pair<Boolean, ILogicalExpression> p = extractAggFunctionsFromExpression(exprRef, gbyWithAgg, aggregateExprToVarExpr, context); if (p.first) { change = true; exprRef.setValue(p.second); } } used.clear(); VariableUtilities.getUsedVariables(op1, used); // increment the count for the ones which are still used for (LogicalVariable v : used) { Integer m = gbyListifyVarsCount.get(v); if (m != null) { gbyListifyVarsCount.put(v, m + 1); } } } break; } case SUBPLAN: { for (LogicalVariable v : used) { Integer m = gbyListifyVarsCount.get(v); if (m != null) { GroupByOperator gbyOp = gbyWithAgg.get(v); if (pushSubplanAsAggIntoGby(opRef, gbyOp, v, gbyListifyVarsCount, gbyWithAgg, gbyAggVarToPlanIndex, context)) { change = true; } else { gbyListifyVarsCount.put(v, m + 1); } } } break; } case GROUP: { List<LogicalVariable> vars = collectOneVarPerAggFromGroupOp((GroupByOperator) op1); if (vars != null) { for (int i = 0; i < vars.size(); i++) { LogicalVariable v = vars.get(i); if (v != null) { gbyListifyVarsCount.put(v, 0); gbyAggVarToPlanIndex.put(v, i); gbyWithAgg.put(v, (GroupByOperator) op1); } } } break; } default: { for (LogicalVariable v : used) { Integer m = gbyListifyVarsCount.get(v); if (m != null) { gbyListifyVarsCount.put(v, m + 1); } } } } return change; }
From source file:com.netflix.nicobar.core.module.ScriptModuleLoaderTest.java
@Test public void testRelinkDependents() throws Exception { // original graph: A->B->C->D long originalCreateTime = 1000; Set<ScriptArchive> updateArchives = new HashSet<ScriptArchive>(); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("A") .addCompilerPluginId("mockPlugin").addModuleDependency("B").build(), originalCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("B") .addCompilerPluginId("mockPlugin").addModuleDependency("C").build(), originalCreateTime)); updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("C") .addCompilerPluginId("mockPlugin").addModuleDependency("D").build(), originalCreateTime)); updateArchives.add(new TestDependecyScriptArchive( new ScriptModuleSpec.Builder("D").addCompilerPluginId("mockPlugin").build(), originalCreateTime)); ScriptModuleListener mockListener = createMockListener(); when(MOCK_COMPILER.shouldCompile(Mockito.any(ScriptArchive.class))).thenReturn(true); when(MOCK_COMPILER.compile(Mockito.any(ScriptArchive.class), Mockito.any(JBossModuleClassLoader.class), Mockito.any(Path.class))).thenReturn(Collections.<Class<?>>emptySet()); ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder().addListener(mockListener) .addPluginSpec(new ScriptCompilerPluginSpec.Builder("mockPlugin") .withPluginClassName(MockScriptCompilerPlugin.class.getName()).build()) .build();//from w w w .j ava 2 s . c o m moduleLoader.updateScriptArchives(updateArchives); // don't need to re-validate since already validated in testReloadWithUpdatedDepdencies reset(mockListener); // update C. should cause C,B,A to be compiled in order updateArchives.clear(); long updatedCreateTime = 2000; updateArchives.add(new TestDependecyScriptArchive(new ScriptModuleSpec.Builder("C") .addCompilerPluginId("mockPlugin").addModuleDependency("D").build(), updatedCreateTime)); moduleLoader.updateScriptArchives(updateArchives); // validate that they were compiled in the updated reverse dependency order InOrder orderVerifier = inOrder(mockListener); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("C", updatedCreateTime), moduleEquals("C", originalCreateTime)); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("B", originalCreateTime), moduleEquals("B", originalCreateTime)); orderVerifier.verify(mockListener).moduleUpdated(moduleEquals("A", originalCreateTime), moduleEquals("A", originalCreateTime)); orderVerifier.verifyNoMoreInteractions(); // validate the post-condition of the module database assertEquals(moduleLoader.getScriptModule("A").getCreateTime(), originalCreateTime); assertEquals(moduleLoader.getScriptModule("B").getCreateTime(), originalCreateTime); assertEquals(moduleLoader.getScriptModule("C").getCreateTime(), updatedCreateTime); assertEquals(moduleLoader.getScriptModule("D").getCreateTime(), originalCreateTime); assertEquals(moduleLoader.getAllScriptModules().size(), 4); }
From source file:com.linkedin.databus.core.TestDbusEventBufferMult.java
@Test public void addRemoveBuffers() throws IOException, ScnNotFoundException, InvalidConfigException, DatabusException, OffsetNotFoundException { createBufMult();//from www . j av a 2s . c om addEvents(); Set<Integer> srcIds = new HashSet<Integer>(2); srcIds.add(1); // total expected events from source 1 is 5 batchReading(srcIds, 5); PhysicalSourceStaticConfig pConfig = convertToPhysicalSourceConfig(_configSource3).build(); LOG.info("one more buffer for " + pConfig); DbusEventBuffer buf = _eventBufferMult.addNewBuffer(pConfig, _config); buf.start(100); // add events to the new buffer byte[] schema = "ABCDEFGHIJKLMNOP".getBytes(Charset.defaultCharset()); for (int i = 100; i < 110; i++) { if (i % 2 == 0) buf.startEvents(); assertTrue(buf.appendEvent(new DbusEventKey(i), pConfig.getPhysicalPartition().getId().shortValue(), (short) 0, // logical source id System.currentTimeMillis(), (short) (i < 105 ? 21 : 22), schema, ("" + i).getBytes(Charset.defaultCharset()), false, null)); if ((i & 1) == 1) buf.endEvents(i); } // read from one old and one new buffer srcIds.clear(); srcIds.add(12); srcIds.add(22); // total expected events 10 - 5 from source 12, and 5 from source 22 batchReading(srcIds, 10); // remove a buf pConfig = convertToPhysicalSourceConfig(_configSource2).build(); _eventBufferMult.removeBuffer(pConfig); _eventBufferMult.deallocateRemovedBuffers(true); srcIds.clear(); srcIds.add(11); boolean failed = false; try { batchReading(srcIds, 5); failed = false; // didn't fail } catch (java.lang.AssertionError ae) { // expected failed = true; } Assert.assertTrue(failed, "should've failed for src 11, since the buffer was removed" + pConfig); }
From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java
@Override public IBundleProvider search(final SearchParameterMap theParams) { StopWatch w = new StopWatch(); final InstantDt now = InstantDt.withCurrentTime(); Set<Long> loadPids; if (theParams.isEmpty()) { loadPids = new HashSet<Long>(); CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> cq = builder.createTupleQuery(); Root<ResourceTable> from = cq.from(ResourceTable.class); cq.multiselect(from.get("myId").as(Long.class)); Predicate typeEquals = builder.equal(from.get("myResourceType"), myResourceName); Predicate notDeleted = builder.isNull(from.get("myDeleted")); cq.where(builder.and(typeEquals, notDeleted)); TypedQuery<Tuple> query = myEntityManager.createQuery(cq); for (Tuple next : query.getResultList()) { loadPids.add(next.get(0, Long.class)); }//from w w w.j a v a 2 s.c om } else { loadPids = searchForIdsWithAndOr(theParams); if (loadPids.isEmpty()) { return new SimpleBundleProvider(); } } final List<Long> pids; // Handle sorting if any was provided if (theParams.getSort() != null && isNotBlank(theParams.getSort().getParamName())) { List<Order> orders = new ArrayList<Order>(); List<Predicate> predicates = new ArrayList<Predicate>(); CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> cq = builder.createTupleQuery(); Root<ResourceTable> from = cq.from(ResourceTable.class); predicates.add(from.get("myId").in(loadPids)); createSort(builder, from, theParams.getSort(), orders, predicates); if (orders.size() > 0) { Set<Long> originalPids = loadPids; loadPids = new LinkedHashSet<Long>(); cq.multiselect(from.get("myId").as(Long.class)); cq.where(predicates.toArray(new Predicate[0])); cq.orderBy(orders); TypedQuery<Tuple> query = myEntityManager.createQuery(cq); for (Tuple next : query.getResultList()) { loadPids.add(next.get(0, Long.class)); } ourLog.info("Sort PID order is now: {}", loadPids); pids = new ArrayList<Long>(loadPids); // Any ressources which weren't matched by the sort get added to the bottom for (Long next : originalPids) { if (loadPids.contains(next) == false) { pids.add(next); } } } else { pids = new ArrayList<Long>(loadPids); } } else { pids = new ArrayList<Long>(loadPids); } // Load _revinclude resources if (theParams.getRevIncludes() != null && theParams.getRevIncludes().isEmpty() == false) { loadReverseIncludes(pids, theParams.getRevIncludes()); } IBundleProvider retVal = new IBundleProvider() { @Override public InstantDt getPublished() { return now; } @Override public List<IResource> getResources(final int theFromIndex, final int theToIndex) { TransactionTemplate template = new TransactionTemplate(myPlatformTransactionManager); return template.execute(new TransactionCallback<List<IResource>>() { @Override public List<IResource> doInTransaction(TransactionStatus theStatus) { List<Long> pidsSubList = pids.subList(theFromIndex, theToIndex); // Execute the query and make sure we return distinct results List<IResource> retVal = new ArrayList<IResource>(); loadResourcesByPid(pidsSubList, retVal, BundleEntrySearchModeEnum.MATCH); /* * Load _include resources - Note that _revincludes are handled differently * than _include ones, as they are counted towards the total count and paged, * so they are loaded outside the bundle provider */ if (theParams.getIncludes() != null && theParams.getIncludes().isEmpty() == false) { Set<IdDt> previouslyLoadedPids = new HashSet<IdDt>(); for (IResource next : retVal) { previouslyLoadedPids.add(next.getId().toUnqualifiedVersionless()); } Set<IdDt> includePids = new HashSet<IdDt>(); List<IResource> resources = retVal; do { includePids.clear(); FhirTerser t = getContext().newTerser(); for (Include next : theParams.getIncludes()) { for (IResource nextResource : resources) { RuntimeResourceDefinition def = getContext() .getResourceDefinition(nextResource); List<Object> values = getIncludeValues(t, next, nextResource, def); for (Object object : values) { if (object == null) { continue; } if (!(object instanceof BaseResourceReferenceDt)) { throw new InvalidRequestException("Path '" + next.getValue() + "' produced non ResourceReferenceDt value: " + object.getClass()); } BaseResourceReferenceDt rr = (BaseResourceReferenceDt) object; if (rr.getReference().isEmpty()) { continue; } if (rr.getReference().isLocal()) { continue; } IdDt nextId = rr.getReference().toUnqualified(); if (!previouslyLoadedPids.contains(nextId)) { includePids.add(nextId); previouslyLoadedPids.add(nextId); } } } } resources = addResourcesAsIncludesById(retVal, includePids, resources); } while (includePids.size() > 0 && previouslyLoadedPids.size() < getConfig().getIncludeLimit()); if (previouslyLoadedPids.size() >= getConfig().getIncludeLimit()) { OperationOutcome oo = new OperationOutcome(); oo.addIssue().setSeverity(IssueSeverityEnum.WARNING).setDetails( "Not all _include resources were actually included as the request surpassed the limit of " + getConfig().getIncludeLimit() + " resources"); retVal.add(0, oo); } } return retVal; } }); } @Override public Integer preferredPageSize() { return theParams.getCount(); } @Override public int size() { return pids.size(); } }; ourLog.info("Processed search for {} on {} in {}ms", new Object[] { myResourceName, theParams, w.getMillisAndRestart() }); return retVal; }
From source file:com.redhat.rhn.frontend.xmlrpc.errata.ErrataHandler.java
/** * Set erratum details./* w w w . j a va 2 s . c om*/ * * @param loggedInUser The current user * @param advisoryName The advisory name of the errata * @param details Map of (optional) erratum details to be set. * @return 1 on success, exception thrown otherwise. * * @xmlrpc.doc Set erratum details. All arguments are optional and will only be modified * if included in the struct. This method will only allow for modification of custom * errata created either through the UI or API. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param("string", "advisoryName") * @xmlrpc.param * #struct("errata details") * #prop("string", "synopsis") * #prop("string", "advisory_name") * #prop("int", "advisory_release") * #prop_desc("string", "advisory_type", "Type of advisory (one of the * following: 'Security Advisory', 'Product Enhancement Advisory', * or 'Bug Fix Advisory'") * #prop("string", "product") * #prop("dateTime.iso8601", "issue_date") * #prop("dateTime.iso8601", "update_date") * #prop("string", "errataFrom") * #prop("string", "topic") * #prop("string", "description") * #prop("string", "references") * #prop("string", "notes") * #prop("string", "solution") * #prop_desc("array", "bugs", "'bugs' is the key into the struct") * #array() * #struct("bug") * #prop_desc("int", "id", "Bug Id") * #prop("string", "summary") * #prop("string", "url") * #struct_end() * #array_end() * #prop_desc("array", "keywords", "'keywords' is the key into the struct") * #array_single("string", "keyword - List of keywords to associate * with the errata.") * #prop_desc("array", "CVEs", "'cves' is the key into the struct") * #array_single("string", "cves - List of CVEs to associate * with the errata. (valid only for published errata)") * #struct_end() * * @xmlrpc.returntype #return_int_success() */ public Integer setDetails(User loggedInUser, String advisoryName, Map<String, Object> details) { Errata errata = lookupErrata(advisoryName, loggedInUser.getOrg()); if (errata.getOrg() == null) { // Errata in the null org should not be modified; therefore, this is // considered an invalid errata for this request throw new InvalidErrataException(errata.getAdvisoryName()); } // confirm that the user only provided valid keys in the map Set<String> validKeys = new HashSet<String>(); validKeys.add("synopsis"); validKeys.add("advisory_name"); validKeys.add("advisory_release"); validKeys.add("advisory_type"); validKeys.add("product"); validKeys.add("issue_date"); validKeys.add("update_date"); validKeys.add("errataFrom"); validKeys.add("topic"); validKeys.add("description"); validKeys.add("references"); validKeys.add("notes"); validKeys.add("solution"); validKeys.add("bugs"); validKeys.add("keywords"); if (errata.isPublished()) { validKeys.add("cves"); } validateMap(validKeys, details); validKeys.clear(); validKeys.add("id"); validKeys.add("summary"); validKeys.add("url"); if (details.containsKey("bugs")) { for (Map<String, Object> bugMap : (ArrayList<Map<String, Object>>) details.get("bugs")) { validateMap(validKeys, bugMap); } } if (details.containsKey("issue_date")) { try { errata.setIssueDate((Date) details.get("issue_date")); } catch (ClassCastException e) { throw new InvalidParameterException("Wrong 'issue_date' format."); } } if (details.containsKey("update_date")) { try { errata.setUpdateDate((Date) details.get("update_date")); } catch (ClassCastException e) { throw new InvalidParameterException("Wrong 'update_date' format."); } } if (details.containsKey("synopsis")) { if (StringUtils.isBlank((String) details.get("synopsis"))) { throw new InvalidParameterException("Synopsis is required."); } errata.setSynopsis((String) details.get("synopsis")); } if (details.containsKey("advisory_name")) { if (StringUtils.isBlank((String) details.get("advisory_name"))) { throw new InvalidParameterException("Advisory name is required."); } errata.setAdvisoryName((String) details.get("advisory_name")); } if (details.containsKey("advisory_release")) { Long rel = new Long((Integer) details.get("advisory_release")); if (rel.longValue() > ErrataManager.MAX_ADVISORY_RELEASE) { throw new InvalidAdvisoryReleaseException(rel.longValue()); } errata.setAdvisoryRel(rel); } if (details.containsKey("advisory_type")) { String pea = "Product Enhancement Advisory"; // hack for checkstyle if (!((String) details.get("advisory_type")).equals("Security Advisory") && !((String) details.get("advisory_type")).equals(pea) && !((String) details.get("advisory_type")).equals("Bug Fix Advisory")) { throw new InvalidParameterException("Invalid advisory type"); } errata.setAdvisoryType((String) details.get("advisory_type")); } if (details.containsKey("product")) { if (StringUtils.isBlank((String) details.get("product"))) { throw new InvalidParameterException("Product name is required."); } errata.setProduct((String) details.get("product")); } if (details.containsKey("errataFrom")) { errata.setErrataFrom((String) details.get("errataFrom")); } if (details.containsKey("topic")) { if (StringUtils.isBlank((String) details.get("topic"))) { throw new InvalidParameterException("Topic is required."); } errata.setTopic((String) details.get("topic")); } if (details.containsKey("description")) { if (StringUtils.isBlank((String) details.get("description"))) { throw new InvalidParameterException("Description is required."); } errata.setDescription((String) details.get("description")); } if (details.containsKey("solution")) { if (StringUtils.isBlank((String) details.get("solution"))) { throw new InvalidParameterException("Solution is required."); } errata.setSolution((String) details.get("solution")); } if (details.containsKey("references")) { errata.setRefersTo((String) details.get("references")); } if (details.containsKey("notes")) { errata.setNotes((String) details.get("notes")); } if (details.containsKey("bugs")) { if (errata.getBugs() != null) { errata.getBugs().clear(); HibernateFactory.getSession().flush(); } for (Map<String, Object> bugMap : (ArrayList<Map<String, Object>>) details.get("bugs")) { if (bugMap.containsKey("id") && bugMap.containsKey("summary")) { String url = null; if (bugMap.containsKey("url")) { url = (String) bugMap.get("url"); } Bug bug = ErrataFactory.createPublishedBug(new Long((Integer) bugMap.get("id")), (String) bugMap.get("summary"), url); errata.addBug(bug); } } } if (details.containsKey("keywords")) { if (errata.getKeywords() != null) { errata.getKeywords().clear(); HibernateFactory.getSession().flush(); } for (String keyword : (ArrayList<String>) details.get("keywords")) { errata.addKeyword(keyword); } } if (details.containsKey("cves")) { if (errata.getCves() != null) { errata.getCves().clear(); HibernateFactory.getSession().flush(); } for (String cveName : (ArrayList<String>) details.get("cves")) { Cve c = CveFactory.lookupByName(cveName); if (c == null) { c = new Cve(); c.setName(cveName); CveFactory.save(c); } errata.getCves().add(c); } } // ALWAYS change the advisory to match, as we do in the UI. errata.setAdvisory(errata.getAdvisoryName() + "-" + errata.getAdvisoryRel().toString()); //Save the errata ErrataManager.storeErrata(errata); return 1; }
From source file:com.doculibre.constellio.wicket.panels.admin.stats.CollectionStatsPanel.java
public CollectionStatsPanel(String id, final String collectionName) { super(id);/*from www .j a va 2s .c o m*/ endDate = new Date(); startDate = DateUtils.addMonths(endDate, -1); Form form = new Form("form") { @Override protected void onSubmit() { statsPanel.replaceWith(statsPanel = new CollectionStatsReportPanel(statsPanel.getId(), collectionName, statsType, startDate, endDate, rows, includeFederatedCollections)); } }; add(form); IModel queryExcludeRegexpsModel = new Model() { @Override public Object getObject() { String result; AdminCollectionPanel adminCollectionPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = adminCollectionPanel.getCollection(); CollectionStatsFilter statsFilter = collection.getStatsFilter(); if (statsFilter != null) { StringBuffer sb = new StringBuffer(); Set<String> existingRegexps = statsFilter.getQueryExcludeRegexps(); for (String existingRegexp : existingRegexps) { sb.append(existingRegexp); sb.append("\n"); } result = sb.toString(); } else { result = null; } return result; } @Override public void setObject(Object object) { String queryExcludeRegexpsStr = (String) object; String[] newRegexpsArray = StringUtils.split(queryExcludeRegexpsStr, "\n"); List<String> newRegexps = new ArrayList<String>(); for (String newRegexp : newRegexpsArray) { newRegexps.add(newRegexp.trim()); } AdminCollectionPanel adminCollectionPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = adminCollectionPanel.getCollection(); CollectionStatsFilter statsFilter = collection.getStatsFilter(); if (statsFilter == null) { statsFilter = new CollectionStatsFilter(); statsFilter.setRecordCollection(collection); collection.setStatsFilter(statsFilter); } Set<String> existingRegexps = statsFilter.getQueryExcludeRegexps(); if (!CollectionUtils.isEqualCollection(existingRegexps, newRegexps)) { RecordCollectionServices collectionServices = ConstellioSpringUtils .getRecordCollectionServices(); EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager(); if (!entityManager.getTransaction().isActive()) { entityManager.getTransaction().begin(); } existingRegexps.clear(); existingRegexps.addAll(newRegexps); collectionServices.makePersistent(collection, false); entityManager.getTransaction().commit(); } } }; form.add(new TextArea("queryExcludeRegexps", queryExcludeRegexpsModel)); form.add(new DateTextField("startDate", new PropertyModel(this, "startDate"), "yyyy-MM-dd") .add(new DatePicker())); form.add(new DateTextField("endDate", new PropertyModel(this, "endDate"), "yyyy-MM-dd") .add(new DatePicker())); form.add(new TextField("rows", new PropertyModel(this, "rows"), Integer.class)); form.add(new CheckBox("includeFederatedCollections", new PropertyModel(this, "includeFederatedCollections")) { @Override public boolean isVisible() { boolean visible = super.isVisible(); if (visible) { AdminCollectionPanel adminCollectionPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = adminCollectionPanel.getCollection(); visible = collection.isFederationOwner(); } return visible ? visible : false; } }); form.add(new DropDownChoice("statsType", new PropertyModel(this, "statsType"), StatsConstants.ALL_STATS, new StringResourceChoiceRenderer("statsType", this))); form.add(new Label("title", new PropertyModel(this, "statsType"))); statsPanel = new AjaxLazyLoadPanel("statsPanel") { @Override public Component getLazyLoadComponent(String markupId) { return new CollectionStatsReportPanel(markupId, collectionName, statsType, startDate, endDate, rows, includeFederatedCollections); } }; form.add(statsPanel); }
From source file:forge.game.phase.PhaseHandler.java
public void startFirstTurn(Player goesFirst) { StopWatch sw = new StopWatch(); if (phase != null) { throw new IllegalStateException("Turns already started, call this only once per game"); }// ww w . j a va 2s. c o m setPlayerTurn(goesFirst); advanceToNextPhase(); onPhaseBegin(); // don't even offer priority, because it's untap of 1st turn now givePriorityToPlayer = false; final Set<Card> allAffectedCards = new HashSet<Card>(); // MAIN GAME LOOP while (!game.isGameOver()) { if (givePriorityToPlayer) { if (DEBUG_PHASES) { sw.start(); } game.fireEvent(new GameEventPlayerPriority(playerTurn, phase, getPriorityPlayer())); List<SpellAbility> chosenSa = null; int loopCount = 0; do { do { // Rule 704.3 Whenever a player would get priority, the game checks ... for state-based actions, game.getAction().checkStateEffects(false, allAffectedCards); if (game.isGameOver()) { return; // state-based effects check could lead to game over } } while (game.getStack().addAllTriggeredAbilitiesToStack()); //loop so long as something was added to stack if (!allAffectedCards.isEmpty()) { game.fireEvent(new GameEventCardStatsChanged(allAffectedCards)); allAffectedCards.clear(); } if (playerTurn.hasLost() && pPlayerPriority.equals(playerTurn) && pFirstPriority.equals(playerTurn)) { // If the active player has lost, and they have priority, set the next player to have priority System.out.println("Active player is no longer in the game..."); pPlayerPriority = game.getNextPlayerAfter(getPriorityPlayer()); pFirstPriority = pPlayerPriority; } chosenSa = pPlayerPriority.getController().chooseSpellAbilityToPlay(); if (chosenSa == null) { break; // that means 'I pass' } if (DEBUG_PHASES) { System.out.print("... " + pPlayerPriority + " plays " + chosenSa); } pFirstPriority = pPlayerPriority; // all opponents have to pass before stack is allowed to resolve for (SpellAbility sa : chosenSa) { pPlayerPriority.getController().playChosenSpellAbility(sa); } loopCount++; } while (loopCount < 999 || !pPlayerPriority.getController().isAI()); if (loopCount >= 999 && pPlayerPriority.getController().isAI()) { System.out.print("AI looped too much with: " + chosenSa); } if (DEBUG_PHASES) { sw.stop(); System.out.print("... passed in " + sw.getTime() / 1000f + " s\n"); System.out.println("\t\tStack: " + game.getStack()); sw.reset(); } } else if (DEBUG_PHASES) { System.out.print(" >> (no priority given to " + getPriorityPlayer() + ")\n"); } // actingPlayer is the player who may act // the firstAction is the player who gained Priority First in this segment // of Priority Player nextPlayer = game.getNextPlayerAfter(getPriorityPlayer()); if (game.isGameOver() || nextPlayer == null) { return; } // conceded? if (DEBUG_PHASES) { System.out.println(String.format("%s %s: %s is active, previous was %s", playerTurn, phase, pPlayerPriority, nextPlayer)); } if (pFirstPriority == nextPlayer) { if (game.getStack().isEmpty()) { if (playerTurn.hasLost()) { setPriority(game.getNextPlayerAfter(playerTurn)); } else { setPriority(playerTurn); } // end phase givePriorityToPlayer = true; onPhaseEnd(); advanceToNextPhase(); onPhaseBegin(); } else if (!game.getStack().hasSimultaneousStackEntries()) { game.getStack().resolveStack(); } } else { // pass the priority to other player pPlayerPriority = nextPlayer; } // If ever the karn's ultimate resolved if (game.getAge() == GameStage.RestartedByKarn) { setPhase(null); game.updatePhaseForView(); game.fireEvent(new GameEventGameRestarted(playerTurn)); return; } } }
From source file:org.apache.hadoop.hdfs.server.blockmanagement.TestReplicationPolicy.java
/** * In this testcase, there are enough total number of nodes, but only * one rack is actually available./*ww w .j a va 2 s . co m*/ * @throws Exception */ @Test public void testChooseTarget6() throws Exception { DatanodeStorageInfo storage = DFSTestUtil.createDatanodeStorageInfo("DS-xxxx", "7.7.7.7", "/d2/r3", "host7"); DatanodeDescriptor newDn = storage.getDatanodeDescriptor(); Set<Node> excludedNodes; List<DatanodeStorageInfo> chosenNodes = new ArrayList<DatanodeStorageInfo>(); excludedNodes = new HashSet<Node>(); excludedNodes.add(dataNodes[0]); excludedNodes.add(dataNodes[1]); excludedNodes.add(dataNodes[2]); excludedNodes.add(dataNodes[3]); DatanodeStorageInfo[] targets; // Only two nodes available in a rack. Try picking two nodes. Only one // should return. targets = chooseTarget(2, chosenNodes, excludedNodes); assertEquals(1, targets.length); // Make three nodes available in a rack. final BlockManager bm = namenode.getNamesystem().getBlockManager(); bm.getDatanodeManager().getNetworkTopology().add(newDn); bm.getDatanodeManager().getHeartbeatManager().addDatanode(newDn); updateHeartbeatWithUsage(newDn, 2 * HdfsServerConstants.MIN_BLOCKS_FOR_WRITE * BLOCK_SIZE, 0L, 2 * HdfsServerConstants.MIN_BLOCKS_FOR_WRITE * BLOCK_SIZE, 0L, 0L, 0L, 0, 0); // Try picking three nodes. Only two should return. excludedNodes.clear(); excludedNodes.add(dataNodes[0]); excludedNodes.add(dataNodes[1]); excludedNodes.add(dataNodes[2]); excludedNodes.add(dataNodes[3]); chosenNodes.clear(); try { targets = chooseTarget(3, chosenNodes, excludedNodes); assertEquals(2, targets.length); } finally { bm.getDatanodeManager().getNetworkTopology().remove(newDn); } }
From source file:org.openmrs.module.personalhr.web.controller.PhrUserFormController.java
/** * @should work for an example/*from w w w . j ava 2s . c o m*/ */ @RequestMapping(value = "/phr/user.form", method = RequestMethod.POST) public String handleSubmission(final WebRequest request, final HttpSession httpSession, final ModelMap model, @RequestParam(required = false, value = "action") final String action, @RequestParam(required = false, value = "userFormPassword") String password, @RequestParam(required = false, value = "secretQuestion") final String secretQuestion, @RequestParam(required = false, value = "secretAnswer") final String secretAnswer, @RequestParam(required = false, value = "confirm") String confirm, @RequestParam(required = false, value = "forcePassword") final Boolean forcePassword, @RequestParam(required = false, value = "roleStrings") final String[] roles, @RequestParam(required = false, value = "createNewPerson") final String createNewPerson, @RequestParam(required = false, value = "sharingToken") String sharingToken, @ModelAttribute("user") final User user, final BindingResult errors) { if (sharingToken == null) { sharingToken = (String) model.get("sharingToken"); } log.debug("Entering PhrUserFormController:handleSubmission..." + sharingToken); //add temporary privileges boolean isTemporary = false; boolean isAdministrator = false; if (!Context.isAuthenticated()) { Context.authenticate("temporary", "Temporary8"); Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS); Context.addProxyPrivilege("PHR Restricted Patient Access"); isTemporary = true; log.debug("Added proxy privileges!"); } else { if (PhrService.PhrBasicRole.PHR_ADMINISTRATOR.getValue() .equals(PersonalhrUtil.getService().getPhrRole(Context.getAuthenticatedUser()))) { isAdministrator = true; Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS); } } try { final UserService us = Context.getUserService(); final MessageSourceService mss = Context.getMessageSourceService(); if (mss.getMessage("User.assumeIdentity").equals(action)) { Context.becomeUser(user.getSystemId()); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success"); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName()); return "redirect:/phr/index.htm"; } else if (mss.getMessage("User.delete").equals(action)) { try { Context.getUserService().purgeUser(user); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success"); return "redirect:/phr/user.list"; } catch (final Exception ex) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.delete.failure"); log.error("Failed to delete user", ex); return "redirect:/phr/user.form?userId=" + request.getParameter("userId"); } } else if (mss.getMessage("User.retire").equals(action)) { final String retireReason = request.getParameter("retireReason"); if (!(StringUtils.hasText(retireReason))) { errors.rejectValue("retireReason", "User.disableReason.empty"); return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession); } else { us.retireUser(user, retireReason); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage"); } } else if (mss.getMessage("User.unRetire").equals(action)) { us.unretireUser(user); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage"); } else { // check if username is already in the database if (us.hasDuplicateUsername(user)) { errors.rejectValue("username", "error.username.taken"); } // check if password and password confirm are identical if ((password == null) || password.equals("XXXXXXXXXXXXXXX")) { password = ""; } if ((confirm == null) || confirm.equals("XXXXXXXXXXXXXXX")) { confirm = ""; } if (!password.equals(confirm)) { errors.reject("error.password.match"); } if ((password.length() == 0) && isNewUser(user)) { errors.reject("error.password.weak"); } //check password strength if (password.length() > 0) { try { OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId()); } catch (final PasswordException e) { errors.reject(e.getMessage()); } } final Set<Role> newRoles = new HashSet<Role>(); if (roles != null) { for (final String r : roles) { // Make sure that if we already have a detached instance of this role in the // user's roles, that we don't fetch a second copy of that same role from // the database, or else hibernate will throw a NonUniqueObjectException. Role role = null; if (user.getRoles() != null) { for (final Role test : user.getRoles()) { if (test.getRole().equals(r)) { role = test; } } } if (role == null) { role = us.getRole(r); user.addRole(role); } newRoles.add(role); } } else { final Role role = us.getRole("PHR Restricted User"); newRoles.add(role); user.addRole(role); log.debug("Added PHR Restricted User role only: " + role); } if (user.getRoles() == null) { newRoles.clear(); } else { user.getRoles().retainAll(newRoles); } final String[] keys = request.getParameterValues("property"); final String[] values = request.getParameterValues("value"); if ((keys != null) && (values != null)) { for (int x = 0; x < keys.length; x++) { final String key = keys[x]; final String val = values[x]; user.setUserProperty(key, val); } } new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword); final UserValidator uv = new UserValidator(); uv.validate(user, errors); if (errors.hasErrors()) { log.debug("errors validating user: " + errors.getErrorCount() + errors.toString()); return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession); } String emailEntered = request.getParameter("9"); if (isNewUser(user) && !isAdministrator) { log.debug("Saving new user " + user.getUsername() + ", sharingToken=" + sharingToken); final PhrSharingToken token = Context.getService(PhrSharingTokenService.class) .getSharingToken(sharingToken); //check token existence and name matching if (token == null || token.getExpireDate().before(new Date())) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Failed to register without a valid sharing token"); log.error("Failed to register without a valid sharing token"); PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null, httpSession.getId(), null, "error=Failed to register without a valid sharing token; user_name=" + user.getName()); if (isTemporary) { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS); Context.removeProxyPrivilege("PHR Restricted Patient Access"); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS); Context.logout(); log.debug("Removed proxy privileges!"); } return "redirect:/phr/index.htm?noredirect=true"; } else if ((token != null) && (token.getRelatedPerson() != null)) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Failed to register with a used sharing token"); log.error("Failed to register with a used sharing token"); PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null, httpSession.getId(), null, "error=Failed to register with a used sharing token; user_name=" + user.getName() + "; sharingToken=" + token); if (isTemporary) { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); Context.removeProxyPrivilege("PHR Restricted Patient Access"); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS); Context.logout(); log.debug("Removed proxy privileges!"); } return "redirect:/phr/index.htm?noredirect=true"; } else if (emailEntered != null && token.getRelatedPersonEmail().equalsIgnoreCase(emailEntered)) { // look for person attributes (including email entered) in the request and save to user for (final PersonAttributeType type : Context.getPersonService() .getPersonAttributeTypes(PERSON_TYPE.PATIENT, ATTR_VIEW_TYPE.VIEWING)) { final String paramName = type.getPersonAttributeTypeId().toString(); final String value = request.getParameter(paramName); this.log.debug("paramName=" + paramName); // if there is an error displaying the attribute, the value will be null if (value != null) { final PersonAttribute attribute = new PersonAttribute(type, value); try { final Object hydratedObject = attribute.getHydratedObject(); if ((hydratedObject == null) || "".equals(hydratedObject.toString())) { // if null is returned, the value should be blanked out attribute.setValue(""); } else if (hydratedObject instanceof Attributable) { attribute.setValue(((Attributable) hydratedObject).serialize()); } else if (!hydratedObject.getClass().getName().equals(type.getFormat())) { // if the classes doesn't match the format, the hydration failed somehow // TODO change the PersonAttribute.getHydratedObject() to not swallow all errors? throw new APIException(); } } catch (final APIException e) { errors.rejectValue("attributeMap[" + type.getName() + "]", "Invalid value for " + type.getName() + ": '" + value + "'"); this.log.warn("Got an invalid value: " + value + " while setting personAttributeType id #" + paramName, e); // setting the value to empty so that the user can reset the value to something else attribute.setValue(""); } user.getPerson().addAttribute(attribute); } } //create a new user by self registration us.saveUser(user, password); //update sharing token token.setRelatedPerson(user.getPerson()); token.setChangedBy(user); final Date date = new Date(); token.setDateChanged(date); token.setActivateDate(date); Context.getService(PhrSharingTokenService.class).savePhrSharingToken(token); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "personalhr.user.signed.up"); log.debug("New self-registered user created: " + user.getUsername()); PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), user, httpSession.getId(), null, "info=New self-registered user created; user_name=" + user.getName() + "; sharingToken=" + token); //save email to messaging service Integer addressId = saveEmail(user.getPerson(), emailEntered); //set default messaging alert address boolean shouldAlert = true; PersonalhrUtil.setMessagingAlertSettings(user.getPerson(), shouldAlert, addressId); //send email notification // TODO get the deployUrl from the request object; also bad to inject /openmrs/ ... final String deployUrl = Context.getRuntimeProperties().getProperty("deployment.url");//"https://65.111.248.164:8443/"; //"172.30.201.24"; final String url = deployUrl + "/openmrs/phr/index.htm"; final String passwordOption = Context.getAdministrationService() .getGlobalProperty("personalhr.show.password"); String notification = NOTIFICATION_TEMPLATE; notification = notification.replaceAll("OPENMRS_PHR_RELATED_PERSON", user.getPerson().getGivenName()); notification = notification.replaceAll("OPENMRS_USERNAME", user.getUsername()); notification = notification.replaceAll("OPENMRS_PASSWORD", showPassword(password, passwordOption)); notification = notification.replaceAll("OPENMRS_URL", url); PersonalhrUtil.sendEmail(emailEntered, notification); } else { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Failed to create new user due to email mismatch: " + emailEntered); log.debug("Failed to create new user due to email mismatch: " + token.getRelatedPersonEmail() + " vs " + emailEntered); PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null, httpSession.getId(), null, "info=Failed to create new user due to email mismatch: " + token.getRelatedPersonEmail() + "vs " + emailEntered + "; sharingToken=" + token); } } else if (isNewUser(user) && isAdministrator) { //create a new user by PHR Administrator us.saveUser(user, password); } else { //modify an exiting user us.saveUser(user, null); if (!password.equals("") && Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) { if (log.isDebugEnabled()) { log.debug("calling changePassword for user " + user + " by user " + Context.getAuthenticatedUser()); } us.changePassword(user, password); } log.debug("Existing user " + user.getUsername() + " changed by user " + Context.getAuthenticatedUser().getUsername()); PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_UPDATE, new Date(), Context.getAuthenticatedUser(), httpSession.getId(), null, "info=Existing user updated; user_name=" + user.getName()); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved"); } if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) { us.changeQuestionAnswer(user, secretQuestion, secretAnswer); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved"); } } } finally { //remove temporary privileges if (isTemporary) { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); Context.removeProxyPrivilege("PHR Restricted Patient Access"); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS); Context.logout(); log.debug("Removed proxy privileges for self registration!"); } else if (isAdministrator) { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS); log.debug("Removed proxy privileges for PHR Administrator!"); } } return "redirect:/phr/index.htm?noredirect=true"; }
From source file:fr.landel.utils.assertor.AssertorIterableTest.java
/** * Test method for {@link AssertorIterable#contains}. * /*w ww. j a v a 2s . com*/ * @throws IOException * On contain */ @Test public void testDoesNotContainIterable() throws IOException { final String el1 = "element1"; final String el2 = "element2"; final Set<String> set = new HashSet<>(); final Set<String> set2 = new HashSet<>(); set.add(el1); set2.add(el1); set2.add(el2); Assertor.that(set).not().containsAll(set2).orElseThrow("iterable contains the list %s*"); Assertor.that(set, EnumAnalysisMode.STREAM).not().containsAll(set2) .orElseThrow("iterable contains the list %s*"); Assertor.that(set, EnumAnalysisMode.PARALLEL).not().containsAll(set2) .orElseThrow("iterable contains the list %s*"); set2.remove(el1); assertException(() -> { Assertor.that(set).not().containsAll(set2).orElseThrow("iterable contains the list %2$s*"); fail(ERROR); }, IllegalArgumentException.class, "iterable contains the list " + set2.toString()); assertException(() -> { Assertor.that(set).not().containsAll(set2).orElseThrow(new IOException(), true); fail(ERROR); }, IOException.class); assertException(() -> { Assertor.that(set).not().containsAll((Iterable<String>) null).orElseThrow(); fail(ERROR); }, IllegalArgumentException.class, "neither iterables can be null or empty"); assertFalse(Assertor.that(set).not().containsAll(set2).isOK()); assertFalse(Assertor.that(set).not().containsAll(set).isOK()); assertTrue(Assertor.that(set).not().containsAny(set2).isOK()); assertFalse(Assertor.that(set).not().containsAny(set).isOK()); set.clear(); assertException(() -> { Assertor.that((Iterable<String>) null).not().containsAll(set2).orElseThrow(); fail(ERROR); }, IllegalArgumentException.class, "neither iterables can be null or empty"); assertException(() -> { Assertor.that(set).not().containsAll((Iterable<String>) null).orElseThrow(); fail(ERROR); }, IllegalArgumentException.class, "neither iterables can be null or empty"); assertFalse(Assertor.that(set).not().containsAll(set2).isOK()); assertFalse(Assertor.that(set).not().containsAll(set).isOK()); assertFalse(Assertor.that(set).not().containsAny(set2).isOK()); assertFalse(Assertor.that(set).not().containsAny(set).isOK()); }