List of usage examples for java.util TreeSet isEmpty
public boolean isEmpty()
From source file:net.firejack.platform.generate.tools.Render.java
/** * @param params//from w w w .j av a 2 s. co m * @return */ public String renderWebServiceParams(TreeSet<ServiceParam> params) { if (params == null || params.isEmpty()) return ""; StringBuilder builder = new StringBuilder(); int i = 0; for (ServiceParam param : params) { String name = param.getName(); ParameterTransmissionType location = param.getLocation(); if (location == null) { builder.append("@WebParam(name = \"request\") ServiceRequest<"); } else { builder.append("@WebParam(name = \"").append(name).append("\") "); } builder.append(renderType(param)); if (location == null) builder.append(">"); builder.append(" ").append(name); if (i < params.size() - 1) { builder.append(","); } i++; } return builder.toString(); }
From source file:org.wso2.andes.kernel.slot.SlotManagerClusterMode.java
/** * Record Slot's last message ID related to a particular queue * * @param queueName name of the queue which this message ID belongs to * @param lastMessageIdInTheSlot last message ID of the slot * @param startMessageIdInTheSlot start message ID of the slot * @param nodeId Node ID of the node that is sending the request. * @param localSafeZone Local safe zone of the requesting node. */// ww w .ja va 2 s.c om public void updateMessageID(String queueName, String nodeId, long startMessageIdInTheSlot, long lastMessageIdInTheSlot, long localSafeZone) throws AndesException { //setting up first message id of the slot if (firstMessageId > startMessageIdInTheSlot || firstMessageId == -1) { firstMessageId = startMessageIdInTheSlot; } if (slotRecoveryScheduled.get()) { queuesToRecover.remove(queueName); } // Read message Id set for slots from store TreeSet<Long> messageIdSet; messageIdSet = slotAgent.getSlotBasedMessageIds(queueName); String lockKey = queueName + SlotManagerClusterMode.class; synchronized (lockKey.intern()) { //Get last assigned message id from database long lastAssignedMessageId = slotAgent.getQueueToLastAssignedId(queueName); // Check if input slot's start message ID is less than last assigned message ID if (startMessageIdInTheSlot < lastAssignedMessageId) { if (log.isDebugEnabled()) { log.debug("Found overlapping slots during slot submit: " + startMessageIdInTheSlot + " to : " + lastMessageIdInTheSlot + ". Comparing to lastAssignedID : " + lastAssignedMessageId); } // Find overlapping slots TreeSet<Slot> overlappingSlots = getOverlappedAssignedSlots(queueName, startMessageIdInTheSlot, lastMessageIdInTheSlot); if (!(overlappingSlots.isEmpty())) { if (log.isDebugEnabled()) { log.debug("Found " + overlappingSlots.size() + " overlapping slots."); } // Following means that we have a piece of the slot exceeding the earliest // assigned slot. breaking that piece and adding it as a new,unassigned slot. if (startMessageIdInTheSlot < overlappingSlots.first().getStartMessageId()) { Slot leftExtraSlot = new Slot(startMessageIdInTheSlot, overlappingSlots.first().getStartMessageId() - 1, queueName); if (log.isDebugEnabled()) { log.debug("Left Extra Slot in overlapping slots : " + leftExtraSlot); } } // This means that we have a piece of the slot exceeding the latest assigned slot. // breaking that piece and adding it as a new,unassigned slot. if (lastMessageIdInTheSlot > overlappingSlots.last().getEndMessageId()) { Slot rightExtraSlot = new Slot(overlappingSlots.last().getEndMessageId() + 1, lastMessageIdInTheSlot, queueName); if (log.isDebugEnabled()) { log.debug("RightExtra in overlapping slot : " + rightExtraSlot); } //Update last message ID - expand ongoing slot to cater this leftover part. slotAgent.addMessageId(queueName, lastMessageIdInTheSlot); if (log.isDebugEnabled()) { log.debug(lastMessageIdInTheSlot + " added to store " + "(RightExtraSlot). Current values in " + "store " + messageIdSet); } } } else { /* * The fact that the slot ended up in this condition means that, all previous slots within this * range have been already processed and deleted. This is a very rare scenario. */ if (log.isDebugEnabled()) { log.debug("A submit slot request has come from the past after deletion of any " + "possible overlapping slots. nodeId : " + nodeId + " StartMessageID : " + startMessageIdInTheSlot + " EndMessageID : " + lastMessageIdInTheSlot); } slotAgent.addMessageId(queueName, lastMessageIdInTheSlot); } } else { //Update the store only if the last assigned message ID is less than the new start message ID slotAgent.addMessageId(queueName, lastMessageIdInTheSlot); if (log.isDebugEnabled()) { log.debug("No overlapping slots found during slot submit " + startMessageIdInTheSlot + " to : " + lastMessageIdInTheSlot + ". Added msgID " + lastMessageIdInTheSlot + " to store"); } } //record local safe zone slotAgent.setLocalSafeZoneOfNode(nodeId, localSafeZone); } }
From source file:net.firejack.platform.generate.tools.Render.java
/** * @param params/* w w w . j av a 2s .c o m*/ * @return */ public String renderEndpointParams(TreeSet<ServiceParam> params) { if (params == null || params.isEmpty()) return ""; StringBuilder builder = new StringBuilder(); int i = 0; for (ServiceParam param : params) { String name = param.getName(); ParameterTransmissionType location = param.getLocation(); if (location == null) { builder.append("ServiceRequest<"); } else if (location.equals(PATH)) { builder.append("@PathParam(\"").append(name).append("\") "); } else if (location.equals(ParameterTransmissionType.QUERY)) { builder.append("@QueryParam(\"").append(name).append("\") "); } builder.append(renderType(param)); if (location == null) builder.append(">"); builder.append(" ").append(name); if (i < params.size() - 1) { builder.append(","); } i++; } return builder.toString(); }
From source file:org.zaproxy.zap.extension.pscanrules.TestInfoSessionIdURL.java
/** * Perform the passive scanning of URL based session IDs * * @param msg the message that need to be checked * @param id the id of the session/*from ww w . ja v a 2 s. co m*/ * @param source the source code of the response */ @Override public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) { TreeSet<HtmlParameter> urlParams = msg.getUrlParams(); String uri = msg.getRequestHeader().getURI().toString(); boolean found = false; // The Session ID list from option param (panel) OptionsParam options = Model.getSingleton().getOptionsParam(); HttpSessionsParam sessionOptions = options.getParamSet(HttpSessionsParam.class); List<String> sessionIds = Collections.emptyList(); if (sessionOptions != null) { sessionIds = sessionOptions.getDefaultTokensEnabled(); } if (!urlParams.isEmpty()) { for (HtmlParameter param : urlParams) { // Iterate through the parameters // If the parameter name is one of those on the Session Token list from the options // panel if (sessionIds.contains(param.getName().toLowerCase(Locale.ROOT))) { // If the param value length is greater than MIN_LENGTH (therefore there is a // value) if (param.getValue().length() > SESSION_TOKEN_MIN_LENGTH) { // Raise an alert according to Passive Scan Rule model // description, uri, param, attack, otherInfo, // solution, reference, evidence, cweId, wascId, msg Alert alert = new Alert(getPluginId(), getRisk(), Alert.CONFIDENCE_HIGH, getName()); alert.setDetail(getDescription(), uri, param.getName(), // param "", // attack "", // otherinfo getSolution(), getReference(), param.getValue(), // evidence getCweId(), // CWE Id getWascId(), // WASC Id - Info leakage msg); parent.raiseAlert(id, alert); // We don't break on this one. // There shouldn't be more than one per URL but bizarre things do happen. // Improbable doesn't mean impossible. found = true; } } } } if (!found && msg.getRequestHeader().getURI().getEscapedPath() != null) { // Handle jsessionid like: // http://tld.gtld/fred;jsessionid=1A530637289A03B07199A44E8D531427?foo=bar Matcher jsessMatcher = null; try { jsessMatcher = Pattern.compile("jsessionid=[\\dA-Z]*", Pattern.CASE_INSENSITIVE) .matcher(msg.getRequestHeader().getURI().getPath()); } catch (URIException e) { } if (jsessMatcher != null && jsessMatcher.find() && sessionIds.contains(jsessMatcher.group().split("=")[0].trim())) { Alert alert = new Alert(getPluginId(), getRisk(), Alert.CONFIDENCE_HIGH, getName()); alert.setDetail(getDescription(), uri, "", // param "", // attack "", // otherinfo getSolution(), getReference(), jsessMatcher.group(), // evidence getCweId(), // CWE Id getWascId(), // WASC Id - Info leakage msg); parent.raiseAlert(id, alert); found = true; } } if (found) { // Now try to check if there exists a referer inside the content // i.e.: There is an external link for which // a referer header would be passed including this session token try { checkSessionIDExposure(msg, id); } catch (URIException e) { } } }
From source file:net.java.sip.communicator.impl.history.HistoryReaderImpl.java
/** * Used to limit the files if any starting or ending date exist * So only few files to be searched./*from w w w . j a va 2 s.co m*/ * * @param filelist Iterator * @param startDate Date * @param endDate Date * @param reverseOrder reverse order of files * @return Vector */ static Vector<String> filterFilesByDate(Iterator<String> filelist, Date startDate, Date endDate, final boolean reverseOrder) { if (startDate == null && endDate == null) { // no filtering needed then just return the same list Vector<String> result = new Vector<String>(); while (filelist.hasNext()) { result.add(filelist.next()); } Collections.sort(result, new Comparator<String>() { public int compare(String o1, String o2) { if (reverseOrder) return o2.compareTo(o1); else return o1.compareTo(o2); } }); return result; } // first convert all files to long TreeSet<Long> files = new TreeSet<Long>(); while (filelist.hasNext()) { String filename = filelist.next(); files.add(Long.parseLong(filename.substring(0, filename.length() - 4))); } TreeSet<Long> resultAsLong = new TreeSet<Long>(); // Temporary fix of a NoSuchElementException if (files.size() == 0) { return new Vector<String>(); } Long startLong; Long endLong; if (startDate == null) startLong = Long.MIN_VALUE; else startLong = startDate.getTime(); if (endDate == null) endLong = Long.MAX_VALUE; else endLong = endDate.getTime(); // get all records inclusive the one before the startdate for (Long f : files) { if (startLong <= f && f <= endLong) { resultAsLong.add(f); } } // get the subset before the start date, to get its last element // if exists if (!files.isEmpty() && files.first() <= startLong) { SortedSet<Long> setBeforeTheInterval = files.subSet(files.first(), true, startLong, true); if (!setBeforeTheInterval.isEmpty()) resultAsLong.add(setBeforeTheInterval.last()); } Vector<String> result = new Vector<String>(); Iterator<Long> iter = resultAsLong.iterator(); while (iter.hasNext()) { Long item = iter.next(); result.add(item.toString() + ".xml"); } Collections.sort(result, new Comparator<String>() { public int compare(String o1, String o2) { if (reverseOrder) return o2.compareTo(o1); else return o1.compareTo(o2); } }); return result; }
From source file:org.wso2.andes.kernel.slot.SlotManager.java
/** * Get an unassigned slot (slots dropped by sudden subscription closes) * * @param queueName name of the queue slot is required * @return slot or null if cannot find//from w ww . j av a 2 s .c om */ private Slot getUnassignedSlot(String queueName) { Slot slotToBeAssigned = null; String lockKey = queueName + SlotManager.class; synchronized (lockKey.intern()) { TreeSetSlotWrapper unAssignedSlotWrapper = unAssignedSlotMap.get(queueName); if (unAssignedSlotWrapper != null) { TreeSet<Slot> slotsFromUnassignedSlotMap = unAssignedSlotWrapper.getSlotTreeSet(); if (slotsFromUnassignedSlotMap != null && !slotsFromUnassignedSlotMap.isEmpty()) { //Get and remove slot and update hazelcast map slotToBeAssigned = slotsFromUnassignedSlotMap.pollFirst(); unAssignedSlotWrapper.setSlotTreeSet(slotsFromUnassignedSlotMap); unAssignedSlotMap.set(queueName, unAssignedSlotWrapper); if (log.isDebugEnabled()) { log.debug("Slot Manager - giving a slot from unAssignedSlotMap. Slot= " + slotToBeAssigned); } } } } return slotToBeAssigned; }
From source file:org.cloudata.core.commitlog.pipe.BufferPool.java
int clearExpiredEntries(int msec) { PoolEntry e = new PoolEntry((System.currentTimeMillis() + 10) - msec); int sizeOfDeallocated = 0; synchronized (bufferMap) { Iterator<TreeSet<PoolEntry>> iter = bufferMap.values().iterator(); while (iter.hasNext()) { TreeSet<PoolEntry> entrySet = iter.next(); SortedSet<PoolEntry> expiredSet = entrySet.headSet(e); if (expiredSet.isEmpty() == false) { LOG.debug(expiredSet.size() + " pool entries are removed"); Iterator<PoolEntry> expiredIter = expiredSet.iterator(); while (expiredIter.hasNext()) { PoolEntry expiredEntry = expiredIter.next(); poolMonitor.deallocated(expiredEntry.buffer.capacity()); sizeOfDeallocated += expiredEntry.buffer.capacity(); }//from www . j a va2s . c o m expiredSet.clear(); if (entrySet.isEmpty()) { LOG.debug("entry set is removed"); iter.remove(); } } } } return sizeOfDeallocated; }
From source file:org.wso2.andes.kernel.slot.SlotManager.java
/** * Create a new slot from slotIDMap/*from w w w . j av a 2 s.co m*/ * * @param queueName name of the queue * @return slot object */ private Slot getFreshSlot(String queueName) { Slot slotToBeAssigned = null; TreeSetLongWrapper wrapper = slotIDMap.get(queueName); TreeSet<Long> messageIDSet; if (wrapper != null) { messageIDSet = wrapper.getLongTreeSet(); if (messageIDSet != null && !messageIDSet.isEmpty()) { //create a new slot slotToBeAssigned = new Slot(); //start msgID will be last assigned ID + 1 so that slots are created with no // message ID gaps in-between Long lastAssignedId = queueToLastAssignedIDMap.get(queueName); if (lastAssignedId != null) { slotToBeAssigned.setStartMessageId(lastAssignedId + 1); } else { slotToBeAssigned.setStartMessageId(0L); } //end messageID will be the lowest in published message ID list. Get and remove slotToBeAssigned.setEndMessageId(messageIDSet.pollFirst()); //set storage queue name (db queue to read messages from) slotToBeAssigned.setStorageQueueName(queueName); //set modified published ID map to hazelcast wrapper.setLongTreeSet(messageIDSet); slotIDMap.set(queueName, wrapper); //modify last assigned ID by queue to hazelcast queueToLastAssignedIDMap.set(queueName, slotToBeAssigned.getEndMessageId()); if (log.isDebugEnabled()) { log.debug("Slot Manager - giving a slot from fresh pool. Slot= " + slotToBeAssigned); } } } return slotToBeAssigned; }
From source file:org.unitime.timetable.gwt.server.UploadServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Params params = null;// w ww . ja va 2 s . c om String q = request.getParameter("q"); if (q != null) { params = new QParams(q); } else { params = new HttpParams(request); } if (params.getParameter("event") != null) { Long eventId = Long.parseLong(params.getParameter("event")); String fileName = params.getParameter("name"); Long noteId = (params.getParameter("note") == null ? null : Long.valueOf(params.getParameter("note"))); if (q == null) getSessionContext().checkPermissionAnyAuthority(Long.valueOf(eventId), "Event", Right.EventDetail); Event event = EventDAO.getInstance().get(eventId); TreeSet<EventNote> notes = new TreeSet<EventNote>(); if (event != null) for (EventNote note : event.getNotes()) { if (note.getAttachedName() == null || note.getAttachedName().isEmpty()) continue; if (fileName != null) { if (fileName.equals(note.getAttachedName()) && (noteId == null || noteId.equals(note.getUniqueId()))) notes.add(note); } else if (noteId != null) { if (noteId.equals(note.getUniqueId())) notes.add(note); } else { notes.add(note); } } if (!notes.isEmpty()) { EventNote note = notes.last(); response.setContentType(note.getAttachedContentType()); response.setHeader("Content-Disposition", "attachment; filename=\"" + note.getAttachedName() + "\""); OutputStream out = response.getOutputStream(); out.write(note.getAttachedFile()); out.flush(); out.close(); return; } } throw new ServletException("Nothing to download."); }
From source file:com.offbynull.voip.kademlia.FindSubcoroutine.java
@Override public List<Node> run(Continuation cnt) throws Exception { Context ctx = (Context) cnt.getContext(); ctx.addOutgoingMessage(subAddress, logAddress, info("Finding {}", findId)); // Set up subcoroutine router Address routerAddress = subAddress.appendSuffix("finderreq" + idGenerator.generate()); SubcoroutineRouter msgRouter = new SubcoroutineRouter(routerAddress, ctx); Controller msgRouterController = msgRouter.getController(); // Get initial set of nodes to query from routing table List<Node> startNodes = router.find(findId, maxResults, false); // do not include stale nodes, we only want to contact alive nodes ctx.addOutgoingMessage(subAddress, logAddress, info("Route table entries closest to {}: {}", findId, startNodes)); // Create sorted set of nodes to contact IdXorMetricComparator idClosenessComparator = new IdXorMetricComparator(findId); TreeSet<Node> contactSet = new TreeSet<>((x, y) -> idClosenessComparator.compare(x.getId(), y.getId())); contactSet.addAll(startNodes);/*from w ww . java2 s . co m*/ // Create a sorted set of nodes to retain closest nodes in TreeSet<Node> closestSet = new TreeSet<>((x, y) -> idClosenessComparator.compare(x.getId(), y.getId())); // Execute requests Map<Subcoroutine<?>, Node> requestSubcoroutineToNodes = new HashMap<>(); // executing requests Set<Id> queriedSet = new HashSet<>(); // ids that have already been queried while (true) { // If there's room left to query more contacts that are closer to findId, do so... while (msgRouterController.size() < maxConcurrentRequests && !contactSet.isEmpty()) { // Get next farthest away node to contact Node contactNode = contactSet.pollLast(); // Add it to set of set of ids that have already been queried.. if it's already there, it means that it's already been // queried by this find, so skip it... boolean added = queriedSet.add(contactNode.getId()); if (!added) { continue; } // Add it to the set of closest nodes (will be removed if node fails to respond) closestSet.add(contactNode); // If we already have maxResult closer nodes to findId, skip this node if (closestSet.size() > maxResults) { Node removedNode = closestSet.pollLast(); if (removedNode == contactNode) { continue; } } // Initialize query Address destinationAddress = addressTransformer.toAddress(contactNode.getLink()) .appendSuffix(ROUTER_EXT_HANDLER_RELATIVE_ADDRESS); RequestSubcoroutine<FindResponse> reqSubcoroutine = new RequestSubcoroutine.Builder<FindResponse>() .sourceAddress(routerAddress, idGenerator).destinationAddress(destinationAddress) .timerAddress(timerAddress) .request(new FindRequest(advertiseSelf ? baseId : null, findId, maxResults)) .addExpectedResponseType(FindResponse.class).attemptInterval(Duration.ofSeconds(2L)) .maxAttempts(5).throwExceptionIfNoResponse(false).build(); ctx.addOutgoingMessage(subAddress, logAddress, info("Querying node {}", contactNode)); // Add query to router msgRouterController.add(reqSubcoroutine, AddBehaviour.ADD_PRIME_NO_FINISH); requestSubcoroutineToNodes.put(reqSubcoroutine, contactNode); } // If there are no more requests running, it means we're finished if (msgRouterController.size() == 0) { ctx.addOutgoingMessage(subAddress, logAddress, info("Find complete: {}", closestSet)); return new ArrayList<>(closestSet); } // Wait for next messange forward to the router cnt.suspend(); ForwardResult fr = msgRouter.forward(); // If a request completed from the forwarded message if (fr.isForwarded() && fr.isCompleted()) { // calling isCompleted by itself may throw an exception, check isForwarded first // Get response FindResponse findResponse = (FindResponse) fr.getResult(); if (findResponse == null) { // If failure, then mark as stale and remove from closest // DONT BOTHER WITH TRYING TO CALCULATE LOCKING/UNLOCKING LOGIC. THE LOGIC WILL BECOME EXTREMELY CONVOLUTED. THE QUERY // DID 5 REQUEST. IF NO ANSWER WAS GIVEN IN THE ALLOTED TIME, THEN MARK AS STALE! Node contactedNode = requestSubcoroutineToNodes.remove(fr.getSubcoroutine()); try { // not allowed to mark self as stale -- we may want to find self, but if we do and it's not responsive dont try to // mark it as stale if (!contactedNode.getId().equals(baseId)) { router.stale(contactedNode); } } catch (NodeNotFoundException nnfe) { // may have been removed (already marked as stale) / may not be in routing tree // Do nothing } closestSet.remove(contactedNode); } else { // If success, then add returned nodes to contacts Node[] nodes = findResponse.getNodes(); contactSet.addAll(Arrays.asList(nodes)); // If we don't want to find our own ID / query ourselves... remove any reference to our own ID in the contactSet // TODO: optimize this by removing before it's added to contactSet if (ignoreSelf) { contactSet.removeIf(x -> x.getId().equals(baseId)); } } } } }