List of usage examples for java.util Map clear
void clear();
From source file:com.vmware.bdd.plugin.ambari.service.AmbariImpl.java
private void createConfigGroups(AmClusterDef clusterDef, Set<AmHostGroupInfo> newAmHostGroupsInfo, Map<String, String> configTypeToService) { logger.info("The new host groups are " + ApiUtils.objectToJson(newAmHostGroupsInfo) + "."); List<ApiConfigGroup> configGroups = new ArrayList<>(); Map<String, ApiConfigGroup> serviceToGroup = new HashMap<>(); for (AmHostGroupInfo amHostGroupInfo : newAmHostGroupsInfo) { // for each nodeGroup with the same number of disks, one set of config group will be created // for each service, one config group will be created, which contains all property types belong to this service serviceToGroup.clear(); List<Map<String, Object>> configs = amHostGroupInfo.getConfigurations(); int i = 1; for (Map<String, Object> map : configs) { for (String type : map.keySet()) { String serviceName = configTypeToService.get(type + ".xml"); if (!amHostGroupInfo.getTag2Hosts().keySet().contains(serviceName)) { continue; }//from w w w . j a v a 2s . c o m ApiConfigGroup confGroup = serviceToGroup.get(serviceName); if (confGroup == null) { confGroup = createConfigGroup(clusterDef, amHostGroupInfo, serviceName); serviceToGroup.put(serviceName, confGroup); } ApiConfigGroupConfiguration sameType = null; for (ApiConfigGroupConfiguration config : confGroup.getApiConfigGroupInfo() .getDesiredConfigs()) { if (config.getType().equals(type)) { sameType = config; break; } } if (sameType == null) { sameType = createApiConfigGroupConf(i, type, serviceName, confGroup); } Map<String, String> property = (Map<String, String>) map.get(type); sameType.getProperties().putAll(property); } } configGroups.addAll(serviceToGroup.values()); } if (configGroups.isEmpty()) { return; } logger.info("Start to create config groups: " + configGroups); apiManager.createConfigGroups(clusterDef.getName(), configGroups); }
From source file:com.hurence.logisland.connect.opc.CommonOpcSourceTask.java
@Override public void start(Map<String, String> props) { setConfigurationProperties(props);//from w ww . j a v a 2 s . c om transferQueue = new LinkedTransferQueue<>(); opcOperations = new SmartOpcOperations<>(createOpcOperations()); ConnectionProfile connectionProfile = createConnectionProfile(); host = connectionProfile.getConnectionUri().getHost(); tagInfoMap = CommonUtils.parseTagsFromProperties(props).stream() .collect(Collectors.toMap(TagInfo::getTagId, Function.identity())); minWaitTime = Math.min(10, tagInfoMap.values().stream().map(TagInfo::getSamplingInterval) .mapToLong(Duration::toMillis).min().getAsLong()); opcOperations.connect(connectionProfile); if (!opcOperations.awaitConnected()) { throw new ConnectException("Unable to connect"); } //set up polling source emission pollingScheduler = Executors.newSingleThreadScheduledExecutor(); streamingThread = Executors.newSingleThreadExecutor(); Map<Duration, List<TagInfo>> pollingMap = tagInfoMap.values().stream() .filter(tagInfo -> StreamingMode.POLL.equals(tagInfo.getStreamingMode())) .collect(Collectors.groupingBy(TagInfo::getSamplingInterval)); final Map<String, OpcData> lastValues = Collections.synchronizedMap(new HashMap<>()); pollingMap.forEach((k, v) -> pollingScheduler.scheduleAtFixedRate(() -> { final Instant now = Instant.now(); v.stream().map(TagInfo::getTagId).map(lastValues::get).filter(Functions.not(Objects::isNull)) .map(data -> Pair.of(now, data)).forEach(transferQueue::add); }, 0, k.toNanos(), TimeUnit.NANOSECONDS)); //then subscribe for all final SubscriptionConfiguration subscriptionConfiguration = new SubscriptionConfiguration() .withDefaultSamplingInterval(Duration.ofMillis(10_000)); tagInfoMap.values().forEach(tagInfo -> subscriptionConfiguration .withTagSamplingIntervalForTag(tagInfo.getTagId(), tagInfo.getSamplingInterval())); running.set(true); streamingThread.submit(() -> { while (running.get()) { try { createSessionIfNeeded(); if (session == null) { return; } session.stream(subscriptionConfiguration, tagInfoMap.keySet().toArray(new String[tagInfoMap.size()])).forEach(opcData -> { if (tagInfoMap.get(opcData.getTag()).getStreamingMode() .equals(StreamingMode.SUBSCRIBE)) { transferQueue.add(Pair.of( hasServerSideSampling() ? opcData.getTimestamp() : Instant.now(), opcData)); } else { lastValues.put(opcData.getTag(), opcData); } }); } catch (Exception e) { if (running.get()) { logger.warn("Stream interrupted while reading from " + host, e); safeCloseSession(); lastValues.clear(); } } } }); }
From source file:ai.grakn.test.graql.analytics.AnalyticsTest.java
@Test public void testDegreeIsPersisted() throws Exception { // TODO: Fix on TinkerGraphComputer assumeFalse(usingTinker());// www . j a va 2 s . co m // create a simple graph RoleType pet = graph.putRoleType("pet"); RoleType owner = graph.putRoleType("owner"); RoleType breeder = graph.putRoleType("breeder"); RelationType mansBestFriend = graph.putRelationType("mans-best-friend").hasRole(pet).hasRole(owner) .hasRole(breeder); EntityType person = graph.putEntityType("person").playsRole(owner).playsRole(breeder); EntityType animal = graph.putEntityType("animal").playsRole(pet); // make one person breeder and owner Entity coco = animal.addEntity(); Entity dave = person.addEntity(); Relation daveBreedsAndOwnsCoco = mansBestFriend.addRelation().putRolePlayer(pet, coco).putRolePlayer(owner, dave); // manual degrees Map<String, Long> referenceDegrees = new HashMap<>(); referenceDegrees.put(coco.getId(), 1L); referenceDegrees.put(dave.getId(), 1L); referenceDegrees.put(daveBreedsAndOwnsCoco.getId(), 2L); // validate graph.commit(); // compute and persist degrees Analytics analytics = new Analytics(graph.getKeyspace(), new HashSet<>(), new HashSet<>()); analytics.degreesAndPersist(); // check degrees are correct graph = factory.getGraph(); GraknGraph finalGraph = graph; referenceDegrees.entrySet().forEach(entry -> { Instance instance = finalGraph.getConcept(entry.getKey()); if (instance.isEntity()) { assertTrue(instance.asEntity().resources().iterator().next().getValue().equals(entry.getValue())); } else if (instance.isRelation()) { assertTrue(instance.asRelation().resources().iterator().next().getValue().equals(entry.getValue())); } }); // check only expected resources exist Collection<String> allConcepts = new ArrayList<>(); ResourceType<Long> rt = graph.getResourceType(Analytics.degree); Collection<Resource<Long>> degrees = rt.instances(); Map<Instance, Long> currentDegrees = new HashMap<>(); degrees.forEach(degree -> { Long degreeValue = degree.getValue(); degree.ownerInstances().forEach(instance -> currentDegrees.put(instance, degreeValue)); }); // check all resources exist and no more assertTrue(CollectionUtils.isEqualCollection(currentDegrees.values(), referenceDegrees.values())); // persist again and check again analytics.degreesAndPersist(); // check only expected resources exist graph = factory.getGraph(); rt = graph.getResourceType(Analytics.degree); degrees = rt.instances(); degrees.forEach(i -> i.ownerInstances().iterator().forEachRemaining(r -> allConcepts.add(r.getId()))); // check degrees are correct GraknGraph finalGraph1 = graph; referenceDegrees.entrySet().forEach(entry -> { Instance instance = finalGraph1.getConcept(entry.getKey()); if (instance.isEntity()) { assertTrue(instance.asEntity().resources().iterator().next().getValue().equals(entry.getValue())); } else if (instance.isRelation()) { assertTrue(instance.asRelation().resources().iterator().next().getValue().equals(entry.getValue())); } }); degrees = rt.instances(); currentDegrees.clear(); degrees.forEach(degree -> { Long degreeValue = degree.getValue(); degree.ownerInstances().forEach(instance -> currentDegrees.put(instance, degreeValue)); }); // check all resources exist and no more assertTrue(CollectionUtils.isEqualCollection(currentDegrees.values(), referenceDegrees.values())); }
From source file:com.redhat.rhn.frontend.xmlrpc.system.test.SystemHandlerTest.java
public void testGetConnectionPath() throws Exception { Server server = ServerFactoryTest.createTestServer(admin, true); // check the initial state of the connection path for the server Object[] results = handler.getConnectionPath(admin, new Integer(server.getId().intValue())); assertEquals(0, results.length);/*from ww w.j a v a2s . c o m*/ // create 2 dummy servers to represent proxys and add them to the // server's 'server path' Server proxy1 = ServerFactoryTest.createTestServer(admin, true); Server proxy2 = ServerFactoryTest.createTestServer(admin, true); Long position1 = new Long(0); Long position2 = new Long(1); WriteMode m = ModeFactory.getWriteMode("test_queries", "insert_into_rhnServerPath"); Map<String, Object> params = new HashMap<String, Object>(); params.put("server_id", server.getId()); params.put("proxy_server_id", proxy1.getId()); params.put("proxy_hostname", proxy1.getName()); params.put("position", position1); m.executeUpdate(params); params.clear(); params.put("server_id", server.getId()); params.put("proxy_server_id", proxy2.getId()); params.put("proxy_hostname", proxy2.getName()); params.put("position", position2); m.executeUpdate(params); // execute test... results = handler.getConnectionPath(admin, new Integer(server.getId().intValue())); assertEquals(2, results.length); assertEquals(proxy1.getId(), ((ServerPath) results[0]).getId()); assertEquals(proxy1.getName(), ((ServerPath) results[0]).getHostname()); assertEquals(proxy2.getId(), ((ServerPath) results[1]).getId()); assertEquals(proxy2.getName(), ((ServerPath) results[1]).getHostname()); }
From source file:org.metis.push.PusherBean.java
/** * This method is called by the web socket container after a new * connection/session has been established with this server endpoint. This * method will attempt to subscribe the client based on any query params and * if no params were provide, will use the URL's extra path info. */// w ww . j ava 2 s . c om public void afterConnectionEstablished(WebSocketSession session) throws Exception { super.afterConnectionEstablished(session); LOG.debug(getBeanName() + ":afterConnectionEstablished - session id = " + session.getId()); // place the session in the global session registry. it will be removed // from the registry when it is closed WdsSocketSession wds = new WdsSocketSession(session); getWdsSessions().put(session.getId(), wds); // based on the query string (if any), attempt to find a SqlStmnt for // this session Map<String, String> map = Utils.getQueryMap(session.getUri().getQuery()); SqlStmnt sqlStmnt = (map == null || map.isEmpty()) ? SqlStmnt.getMatch(getSqlStmnts4Get(), null) : SqlStmnt.getMatch(getSqlStmnts4Get(), map.keySet()); // if statement was not found and query params were provided, then // close connection because search for statement had to take place based // on query params provided. in other words, if client provides query // params then it is requesting a subscrption via those params. if (sqlStmnt == null && (map != null && !map.isEmpty())) { LOG.error(getBeanName() + ":afterConnectionEstablished - unable to find sql " + "statement with this incoming param set: " + map.toString()); session.close(POLICY_VIOLATION); return; } // if statement was not found and params were not provided, then attempt // to find statement based on the url's "extra path" info if (sqlStmnt == null) { LOG.trace(getBeanName() + ":afterConnectionEstablished - unable to find sql " + "statement on first pass, will attempt to use extra path info"); String[] xtraPathInfo = Utils.getExtraPathInfo(session.getUri().toString()); if (xtraPathInfo != null && xtraPathInfo.length >= 2) { LOG.debug(getBeanName() + ": extra path key:value = " + xtraPathInfo[0] + ":" + xtraPathInfo[1]); // put the xtra path info in the bucket and try again map = (map == null) ? new HashMap<String, String>() : map; map.clear(); map.put(xtraPathInfo[0], xtraPathInfo[1]); // try again with the extra path info sqlStmnt = SqlStmnt.getMatch(getSqlStmnts4Get(), map.keySet()); // if statement could not be found, then simply return - client // may later subscribe with valid params if (sqlStmnt == null) { LOG.debug(getBeanName() + ":findStmnt - unable to find sql " + "statement with this xtra path info: " + map.toString()); return; } } else { // there was no extra path info, so simply return return; } } mainLock.lock(); try { // if we've gotten this far, a SqlStmnt was found based on query or // extra path info, now see if SqlStmnt already has a job with the // same param set (map). if no job was found, then create and start // one if (sqlStmnt.findSqlJob(map, wds) == null) { sqlStmnt.createSqlJob(map, wds); } } finally { mainLock.unlock(); } }
From source file:com.espertech.esper.core.EPRuntimeIsolatedImpl.java
private void processMatches(EventBean event) { // get matching filters ArrayBackedCollection<FilterHandle> matches = matchesArrayThreadLocal.get(); services.getFilterService().evaluate(event, matches, isolatedTimeEvalContext); if (ThreadLogUtil.ENABLED_TRACE) { ThreadLogUtil.trace("Found matches for underlying ", matches.size(), event.getUnderlying()); }//from w w w .ja v a 2 s .c o m if (matches.size() == 0) { return; } Map<EPStatementHandle, ArrayDeque<FilterHandleCallback>> stmtCallbacks = matchesPerStmtThreadLocal.get(); Object[] matchArray = matches.getArray(); int entryCount = matches.size(); for (int i = 0; i < entryCount; i++) { EPStatementHandleCallback handleCallback = (EPStatementHandleCallback) matchArray[i]; EPStatementHandle handle = handleCallback.getEpStatementHandle(); // Self-joins require that the internal dispatch happens after all streams are evaluated. // Priority or preemptive settings also require special ordering. if (handle.isCanSelfJoin() || isPrioritized) { ArrayDeque<FilterHandleCallback> callbacks = stmtCallbacks.get(handle); if (callbacks == null) { callbacks = new ArrayDeque<FilterHandleCallback>(); stmtCallbacks.put(handle, callbacks); } callbacks.add(handleCallback.getFilterCallback()); continue; } processStatementFilterSingle(handle, handleCallback, event); } matches.clear(); if (stmtCallbacks.isEmpty()) { return; } for (Map.Entry<EPStatementHandle, ArrayDeque<FilterHandleCallback>> entry : stmtCallbacks.entrySet()) { EPStatementHandle handle = entry.getKey(); ArrayDeque<FilterHandleCallback> callbackList = entry.getValue(); processStatementFilterMultiple(handle, callbackList, event); if ((isPrioritized) && (handle.isPreemptive())) { break; } } stmtCallbacks.clear(); }
From source file:gov.nih.nci.ncicb.cadsr.contexttree.service.impl.CDEBrowserTreeServiceImpl.java
/** * @returns a map with contextid as key and value a list of template nodes *///from ww w .j av a 2 s. c om public Map getAllContextTemplateNodes(TreeFunctions treeFunctions, TreeIdGenerator idGen) throws Exception { Map allTemplatesByContext = new HashMap(); Map protoCSMap = this.getFormClassificationNodes(treeFunctions, idGen, CaDSRConstants.TEMPLATE_CS_TYPE, CaDSRConstants.TEMPLATE_CSI_TYPE); Map treeNodeMap = new HashMap(); FormDAO dao = daoFactory.getFormDAO(); List templates = dao.getAllTemplatesOrderByContext(); Iterator iter = templates.iterator(); while (iter.hasNext()) { Form currTemplate = (Form) iter.next(); String currContextId = currTemplate.getContext().getConteIdseq(); Map currCSMap = (Map) protoCSMap.get(currContextId); DefaultMutableTreeNode tmpNode = getTemplateNode(idGen.getNewId(), currTemplate, treeFunctions); DefaultMutableTreeNode tmpLabelNode = (DefaultMutableTreeNode) allTemplatesByContext.get(currContextId); if (tmpLabelNode == null) { tmpLabelNode = getWebNode("Protocol Form Templates", idGen.getNewId()); treeNodeMap.clear(); } allTemplatesByContext.put(currContextId, tmpLabelNode); if (currTemplate.getClassifications() == null || currTemplate.getClassifications().size() == 0) { tmpLabelNode.add(tmpNode); } else { //template nodes need to be added to the cs tree copyCSTree(currTemplate, currCSMap, treeNodeMap, tmpNode, tmpLabelNode, idGen); } } return allTemplatesByContext; }
From source file:fragment.web.UsersControllerTest.java
@Test public void testeditPrefs() throws Exception { User user = userService.getUserByParam("id", "3", false); UserForm form = new UserForm(); form.setCountryList(countryService.getCountries(null, null, null, null, null, null, null)); form.setUser((com.citrix.cpbm.access.User) CustomProxy.newInstance(user)); MockHttpServletRequest mockRequest = new MockHttpServletRequest(); BindingResult bindingResult = validate(form); Map<String, String> controllerMap = controller.editPrefs(form, bindingResult, VALID_TIMEZONE, Locale.ENGLISH.toString(), map, mockRequest); Assert.assertNotNull(controllerMap); Assert.assertEquals(user.getTimeZone(), VALID_TIMEZONE); Assert.assertEquals(user.getLocale(), Locale.ENGLISH); Assert.assertTrue(controllerMap.containsKey("timeZone")); Assert.assertTrue(controllerMap.containsKey("locale")); Assert.assertTrue(controllerMap.containsKey("lastLogin")); Assert.assertEquals(controllerMap.get("timeZone"), VALID_TIMEZONE); Assert.assertEquals(controllerMap.get("locale").toString(), new String("English/US")); controllerMap.clear(); controllerMap = controller.editPrefs(form, null, null, null, map, mockRequest); user = userService.getUserByParam("id", "3", false); Assert.assertNull(user.getLocale()); }
From source file:com.impetus.client.oraclenosql.OracleNoSQLClient.java
/** * Execute./*from w ww . j a v a2 s . c om*/ * * @param batches * the batches */ private void execute(Map<Key, List<TableOperation>> batches) { if (batches != null && !batches.isEmpty()) { try { for (List<TableOperation> batch : batches.values()) { tableAPI.execute(batch, null); } } catch (DurabilityException e) { log.error("Error while executing operations in OracleNOSQL, Caused by:" + e + "."); throw new PersistenceException("Error while Persisting data using batch", e); } catch (TableOpExecutionException e) { log.error("Error while executing operations in OracleNOSQL, Caused by:" + e + "."); throw new PersistenceException("Error while Persisting data using batch", e); } catch (FaultException e) { log.error("Error while executing operations in OracleNOSQL, Caused by:" + e + "."); throw new PersistenceException("Error while Persisting data using batch", e); } finally { batches.clear(); } } }
From source file:org.shredzone.cilla.plugin.flattr.collector.CollectingClickExecutor.java
@Override public synchronized void run() { final List<SomeThingId> thingCollection = new ArrayList<>(); final Map<String, Thing> thingResult = new HashMap<>(); while (true) { try {//from w w w . j av a2 s . com synchronized (this) { while (queue.isEmpty()) { wait(); } ; } if (collectDelay > 0) { Thread.sleep(collectDelay); } synchronized (this) { while (!queue.isEmpty() && processQueue.size() < collectMaxItems) { processQueue.add(queue.remove()); } } thingCollection.clear(); thingCollection .addAll(processQueue.stream().map(ClickFuture::getThingId).collect(Collectors.toList())); GetThingsFromCollectionMethod method = new GetThingsFromCollectionMethod(thingCollection); List<Thing> things = flattrQueue.submit(method).get(); for (Thing t : things) { thingResult.put(t.getThingId(), t); thingCollection.remove(new SomeThingId(t)); } if (!thingCollection.isEmpty()) { log.debug("Could not find some flattr counts"); thingCollection.forEach(flattrPublicationService::unpublished); } } catch (ExecutionException ex) { Throwable t = ex.getCause(); if (t instanceof NotFoundException) { log.debug("Could not find all flattr counts", t); for (SomeThingId tid : thingCollection) { flattrPublicationService.unpublished(tid); } } else { log.error("Cound not bulk get flattr counts", ex); } } catch (InterruptedException ex) { log.error("Cound not bulk get flattr counts", ex); } finally { // Make sure all ClickCallables are going to be triggered... processQueue.forEach(c -> c.filterResult(thingResult)); // ...and feed the GC thingCollection.clear(); thingResult.clear(); processQueue.clear(); } } }