List of usage examples for java.util Set remove
boolean remove(Object o);
From source file:com.almende.eve.ggdemo.HolonAgent.java
public void handleGoal(@Name("goal") Goal goal, @Sender String sender) throws IOException, JSONRPCException, JsonProcessingException { String parent = getState().get("parent", String.class); if (parent != null) { System.err.println(getId() + ": HandleGoal received, sending it to my parent:" + parent); ObjectNode params = JOM.createObjectNode(); params.put("goal", JOM.getInstance().valueToTree(goal)); sendAsync(URI.create(parent), "handleGoal", params, null, Void.class); } else {/*from w w w . j av a 2 s. com*/ System.err.println(getId() + ": HandleGoal received, handling it myself"); Set<String> nbs = new HashSet<String>(neighbours); ArrayList<Sub> subs = getState().get("subs", type); int subSize = 0; if (subs != null) { for (Sub sub : subs) { nbs.remove(sub.getAddress()); subSize += sub.getSize(); } } Integer pointer = getState().get(goal.getId(), Integer.class); if (pointer == null) { for (int i = 0; i < nbs.size(); i++) { if (nbs.toArray(new String[0])[i].equals(sender)) { pointer = i; } } if (pointer == null) { pointer = 0; } } Integer stepSize = getState().get("stepSize", Integer.class); if (!getState().containsKey(goal.getId())) { // Determine my own influence on the goal double noOn = (goal.getPercentage() * goal.getAgentCnt()) / 100; goal.setAgentCnt(goal.getAgentCnt() + subSize + 1); double max = (((noOn + subSize + 1) * 100) / (goal.getAgentCnt())); double min = (((noOn) * 100) / (goal.getAgentCnt())); int subOn = -1; if (max < goal.getGoalPct()) { subOn = subSize + 1; } else if (min > goal.getGoalPct()) { subOn = 0; } else { double noLampsOn = (goal.getGoalPct() * goal.getAgentCnt()) / 100; subOn = (int) Math.round(noLampsOn - noOn); } handleTask(subOn, null); goal.setPercentage((noOn + subOn) * 100 / goal.getAgentCnt()); goal.setTtl(0); } else { goal.setTtl(goal.getTtl() + 1); } getState().put("goal", goal); if (goal.getTtl() > 15) { // No changes, drop this goal. return; } if (nbs.size() == 0) { return; } // Send goal further to neighbours ObjectNode params = JOM.createObjectNode(); params.put("goal", JOM.getInstance().valueToTree(goal)); int count = 0; int original_pointer = pointer; boolean stop = false; while (count < stepSize && !stop) { String neighbour = nbs.toArray(new String[0])[pointer]; pointer++; if (pointer >= nbs.size()) { pointer = 0; } getState().put(goal.getId(), pointer); if (nbs.size() > 1) { if (neighbour.equals(sender)) { continue; } if (pointer == original_pointer) { stop = true; } } count++; sendAsync(URI.create(neighbour), "handleGoal", params, null, Void.class); } } }
From source file:com.zimbra.cs.mime.MimeTest.java
@Test public void imgNoCid() throws Exception { String content = baseMpMixedContent + "------------1111971890AC3BB91\r\n" + "Content-Type: text/html; charset=windows-1250\r\n" + "Content-Transfer-Encoding: quoted-printable\r\n\r\n" + "<html>Email no img</html>\r\n" + "------------1111971890AC3BB91\r\n" + "Content-Type: image/jpeg;\r\n" + "name=\"img.jpg\"\r\n" + "Content-Transfer-Encoding: base64\r\n\r\n" //no CID here, so sender means for us to show it as body + "R0a1231312ad124svsdsal=="; //obviously not a real image MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession(), new SharedByteArrayInputStream(content.getBytes())); List<MPartInfo> parts = Mime.getParts(mm); Assert.assertNotNull(parts);/*w w w .ja v a 2 s . com*/ Assert.assertEquals(3, parts.size()); MPartInfo mpart = parts.get(0); Assert.assertEquals("multipart/mixed", mpart.getContentType()); List<MPartInfo> children = mpart.getChildren(); Assert.assertEquals(2, children.size()); Set<MPartInfo> bodies = Mime.getBody(parts, false); Assert.assertEquals(2, bodies.size()); Set<String> types = Sets.newHashSet("text/html", "image/jpeg"); for (MPartInfo body : bodies) { Assert.assertTrue("Expected: " + body.getContentType(), types.remove(body.getContentType())); } }
From source file:com.aliasi.lingmed.medline.DownloadMedline.java
private String[] subtract(Set<String> setA, Set<String> setB) { Iterator<String> it = setB.iterator(); while (it.hasNext()) { setA.remove(it.next()); }/* ww w .j av a 2s . c om*/ String[] result = new String[setA.size()]; result = setA.toArray(result); StringComparator byName = new StringComparator(); Arrays.sort(result, byName); // mLogger.debug("result=" + java.util.Arrays.asList(result)); return result; }
From source file:hu.netmind.beankeeper.modification.impl.ModificationTrackerImpl.java
private void modifyClassEntries(Class currentClass, ModificationEntry entry, boolean add) { if (currentClass == null) return;//ww w . ja va 2 s .c o m // Do current class Set entries = (Set) entriesByClass.get(currentClass); if (entries == null) { entries = new HashSet(); entriesByClass.put(currentClass, entries); } if (add) entries.add(entry); else entries.remove(entry); if (entries.size() == 0) entriesByClass.remove(currentClass); // Do superclass modifyClassEntries(currentClass.getSuperclass(), entry, add); // Do interfaces Class interfaces[] = currentClass.getInterfaces(); for (int i = 0; i < interfaces.length; i++) modifyClassEntries(interfaces[i], entry, add); }
From source file:org.pathirage.freshet.helpers.WikipediaActivityFeed.java
public void unlisten(String channel, WikipediaFeedListener listener) { Set<WikipediaFeedListener> listeners = channelListeners.get(channel); if (listeners == null) { throw new RuntimeException("Trying to unlisten to a channel that has no listeners in it."); } else if (!listeners.contains(listener)) { throw new RuntimeException("Trying to unlisten to a channel that listener is not listening to."); }/* w w w . ja v a2s . c om*/ listeners.remove(listener); if (listeners.size() == 0) { leave(channel); } }
From source file:com.zia.freshdocs.widget.CMISAdapter.java
/** * Saves the content node to the favorites area of the sdcard * @param position// w w w .j a v a 2 s. co m */ public void toggleFavorite(int position) { final Context context = getContext(); final CMISPreferencesManager prefsMgr = CMISPreferencesManager.getInstance(); final NodeRef ref = getItem(position); final Set<NodeRef> favorites = prefsMgr.getFavorites(context); if (favorites.contains(ref)) { favorites.remove(ref); prefsMgr.storeFavorites(context, favorites); if (_favoritesView) { remove(ref); notifyDataSetChanged(); } } else { downloadContent(ref, new Handler() { public void handleMessage(Message msg) { boolean done = msg.getData().getBoolean("done"); if (done) { dismissProgressDlg(); File file = (File) _dlThread.getResult(); if (file != null) { favorites.add(ref); prefsMgr.storeFavorites(context, favorites); } } else { int value = msg.getData().getInt("progress"); if (value > 0) { _progressDlg.setProgress(value); } } } }); } }
From source file:com.alibaba.dubbo.governance.web.governance.module.screen.Accesses.java
/** * //ww w .j a v a 2 s . c o m * @throws ParseException */ public boolean delete(Map<String, Object> context) throws ParseException { String accesses = (String) context.get("accesses"); String[] temp = accesses.split(" "); Map<String, Set<String>> prepareToDeleate = new HashMap<String, Set<String>>(); for (String s : temp) { String service = s.split("=")[0]; String address = s.split("=")[1]; Set<String> addresses = prepareToDeleate.get(service); if (addresses == null) { prepareToDeleate.put(service, new HashSet<String>()); addresses = prepareToDeleate.get(service); } addresses.add(address); } for (Entry<String, Set<String>> entry : prepareToDeleate.entrySet()) { String service = entry.getKey(); List<Route> routes = routeService.findForceRouteByService(service); if (routes == null || routes.size() == 0) { continue; } for (Route blackwhitelist : routes) { MatchPair pairs = RouteRule.parseRule(blackwhitelist.getMatchRule()).get("consumer.host"); Set<String> matches = new HashSet<String>(); matches.addAll(pairs.getMatches()); Set<String> unmatches = new HashSet<String>(); unmatches.addAll(pairs.getUnmatches()); for (String pair : pairs.getMatches()) { for (String address : entry.getValue()) { if (pair.equals(address)) { matches.remove(pair); break; } } } for (String pair : pairs.getUnmatches()) { for (String address : entry.getValue()) { if (pair.equals(address)) { unmatches.remove(pair); break; } } } if (matches.size() == 0 && unmatches.size() == 0) { routeService.deleteRoute(blackwhitelist.getId()); } else { Map<String, MatchPair> condition = new HashMap<String, MatchPair>(); condition.put("consumer.host", new MatchPair(matches, unmatches)); StringBuilder sb = new StringBuilder(); RouteRule.contidionToString(sb, condition); blackwhitelist.setMatchRule(sb.toString()); routeService.updateRoute(blackwhitelist); } } } return true; }
From source file:com.servioticy.dispatcher.bolts.StreamProcessorBolt.java
public void execute(Tuple input) { SensorUpdate su;/*from w ww . jav a 2s . c o m*/ FutureRestResponse previousSURR; SensorUpdate previousSU; SO so; String soId = input.getStringByField("soid"); String streamId = input.getStringByField("streamid"); String suDoc = input.getStringByField("su"); String soDoc = input.getStringByField("so"); String originId = input.getStringByField("originid"); SOProcessor sop; long timestamp; Map<String, SensorUpdate> sensorUpdates; Map<String, FutureRestResponse> streamSURRs; Map<String, FutureRestResponse> groupSURRs; try { su = this.mapper.readValue(suDoc, SensorUpdate.class); so = this.mapper.readValue(soDoc, SO.class); sop = SOProcessor.factory(so, this.mapper); // Begin all HTTP requests previousSURR = this.getStreamSUAsyncResponse(streamId, so); Set<String> docIds = sop.getSourceIdsByStream(streamId); // Remove the origin for which we already have the SU docIds.remove(originId); docIds.add(streamId); streamSURRs = this.getStreamSUAsyncResponses(docIds, so); groupSURRs = this.getGroupSUAsyncResponses(docIds, so); /*if(suCache.check(soId + ";" + streamId, su.getLastUpdate())){ // This SU or a posterior one has already been sent, do not send this one. this.collector.emit("benchmark", input, new Values(suDoc, System.currentTimeMillis(), "sucache") ); collector.ack(input); return; }*/ if (sop.getClass() == SOProcessor010.class) { // It is not needed to replace the alias, it has been already done in the previous bolt. ((SOProcessor010) sop).compileJSONPaths(); } // Get the last update from the current stream previousSU = this.getStreamSU(previousSURR); // There is already a newer generated update than the one received if (previousSU != null) { if (su.getLastUpdate() <= previousSU.getLastUpdate()) { BenchmarkBolt.send(collector, input, dc, suDoc, "old"); collector.ack(input); return; } } // At this point we know for sure that at least one input SU is newer sensorUpdates = new HashMap<String, SensorUpdate>(); try { sensorUpdates.putAll(this.getStreamSUs(streamSURRs)); sensorUpdates.put(streamId, previousSU); sensorUpdates.putAll(this.getGroupSUs(groupSURRs)); sensorUpdates.put(originId, su); } catch (Exception e) { // TODO Log the error e.printStackTrace(); collector.fail(input); return; } // Obtain the highest timestamp from the input docs timestamp = su.getLastUpdate(); for (Map.Entry<String, SensorUpdate> doc : sensorUpdates.entrySet()) { SensorUpdate inputSU; inputSU = doc.getValue(); if (inputSU == null) { continue; } timestamp = inputSU.getLastUpdate() > timestamp ? inputSU.getLastUpdate() : timestamp; } SensorUpdate resultSU; String resultSUDoc; try { resultSU = sop.getResultSU(streamId, sensorUpdates, originId, timestamp); if (resultSU == null) { BenchmarkBolt.send(collector, input, dc, suDoc, "filtered"); collector.ack(input); return; } resultSUDoc = this.mapper.writeValueAsString(resultSU); } catch (ScriptException e) { // TODO Log the error e.printStackTrace(); BenchmarkBolt.send(collector, input, dc, suDoc, "script-error"); collector.ack(input); return; } if (dc.benchmark) { String[] fromStr = { so.getId(), streamId }; resultSU.setTriggerPath(su.getTriggerPath()); resultSU.setPathTimestamps(su.getPathTimestamps()); resultSU.setOriginId(su.getOriginId()); resultSU.getTriggerPath().add(new ArrayList<String>(Arrays.asList(fromStr))); resultSU.getPathTimestamps().add(System.currentTimeMillis()); } resultSUDoc = this.mapper.writeValueAsString(resultSU); // generate opid String opid = Integer.toHexString(resultSUDoc.hashCode()); // The output update descriptor UpdateDescriptor ud = new UpdateDescriptor(); ud.setSoid(soId); ud.setStreamid(streamId); ud.setOpid(opid); ud.setSu(resultSU); String upDescriptorDoc = this.mapper.writeValueAsString(ud); // Put to the queue try { if (!qc.isConnected()) { qc.connect(); } if (!qc.put(upDescriptorDoc)) { // TODO Log the error System.err.println("Error trying to queue a SU"); collector.fail(input); return; } qc.disconnect(); } catch (Exception e) { // TODO Log the error e.printStackTrace(); collector.fail(input); return; } // Remove the data that doesn't need to be stored. resultSU.setTriggerPath(null); resultSU.setPathTimestamps(null); resultSU.setOriginId(null); resultSUDoc = this.mapper.writeValueAsString(resultSU); // Send to the API restClient.restRequest(dc.restBaseURL + "private/" + soId + "/streams/" + streamId + "/" + opid, resultSUDoc, RestClient.PUT, null); } catch (RestClientErrorCodeException e) { // TODO Log the error e.printStackTrace(); if (e.getRestResponse().getHttpCode() >= 500) { collector.fail(input); return; } BenchmarkBolt.send(collector, input, dc, suDoc, "error"); collector.ack(input); return; } catch (Exception e) { // TODO Log the error BenchmarkBolt.send(collector, input, dc, suDoc, "error"); collector.ack(input); return; } //suCache.put(soId+";"+streamId, su.getLastUpdate()); collector.ack(input); return; }
From source file:com.almende.dht.rpc.DHT.java
/** * Store the value at the key. (Kademlia's STORE) * * @param key//from w ww . jav a 2 s. co m * the key * @param value * the value * @param remote * the remote * @param sender * the sender */ @Access(AccessType.PUBLIC) public void store(@Name("key") Key key, @Name("value") ObjectNode value, @Name("me") Key remote, @Sender URI sender) { rt.seenNode(new Node(remote, sender)); Set<TimedValue> current = new TreeSet<TimedValue>(); TimedValue tv = new TimedValue(value); if (values.containsKey(key)) { current = values.get(key); } current.remove(tv); current.add(tv); values.put(key, current); }