List of usage examples for java.util Deque peek
E peek();
From source file:com.reprezen.swaggerparser.test.BigParseTest.java
private Optional<? extends JsonOverlay<?>> getField(ObjectOverlay<?> modelObj, Deque<PathKey> path) throws IllegalArgumentException, IllegalAccessException { String key = ""; boolean first = true; Optional<? extends JsonOverlay<?>> value = Optional.absent(); if (path.peek() != null && path.peek().isIndex()) { // next path item is an index, so our only shot is to get a list overlay bound directly to this object's // json node value = modelObj.getFieldValue(""); if (value.isPresent() && (value.get() instanceof ListOverlay || value.get() instanceof ValListOverlay)) { return value; }// ww w. ja v a 2 s . c o m } while (!value.isPresent()) { if (path.peek() == null || path.peek().isIndex()) { break; } String next = path.remove().getString(); key = first ? next : key + ":" + next; value = modelObj.getFieldValue(key); first = false; } return value; }
From source file:com.spotify.helios.agent.QueueingHistoryWriter.java
private TaskStatusEvent findEldestEvent() { // We don't lock anything because in the worst case, we just put things in out of order which // while not perfect, won't cause any actual harm. Out of order meaning between jobids, not // within the same job id. Whether this is the best strategy (as opposed to fullest deque) // is arguable. TaskStatusEvent current = null;//from w w w. jav a 2 s. com for (Deque<TaskStatusEvent> queue : items.values()) { if (queue == null) { continue; } final TaskStatusEvent item = queue.peek(); if (current == null || (item.getTimestamp() < current.getTimestamp())) { current = item; } } return current; }
From source file:com.spotify.helios.agent.TaskHistoryWriter.java
private TaskStatusEvent findEldestEvent() { // We don't lock anything because in the worst case, we just put things in out of order which // while not perfect, won't cause any actual harm. Out of order meaning between jobids, not // within the same job id. Whether this is the best strategy (as opposed to fullest deque) // is arguable. TaskStatusEvent current = null;// w ww .j a v a 2 s.co m for (final Deque<TaskStatusEvent> queue : items.values()) { if (queue == null) { continue; } final TaskStatusEvent item = queue.peek(); if (current == null || (item.getTimestamp() < current.getTimestamp())) { current = item; } } return current; }
From source file:com.spotify.helios.agent.QueueingHistoryWriter.java
private TaskStatusEvent getNext() { // Some explanation: We first find the eldest event from amongst the queues (ok, they're // deques, but we really use it as a put back queue), and only then to we try to get // a lock on the relevant queue from whence we got the event. Assuming that all worked // *and* that the event we have wasn't rolled off due to max-size limitations, we then // pull the item off the queue and return it. We're basically doing optimistic concurrency, // and skewing things so that adding to this should be cheap. while (true) { final TaskStatusEvent current = findEldestEvent(); // Didn't find anything that needed processing? if (current == null) { return null; }// w w w . ja va 2 s . c o m final JobId id = current.getStatus().getJob().getId(); final Deque<TaskStatusEvent> deque = items.get(id); if (deque == null) { // shouldn't happen because we should be the only one pulling items off, but.... continue; } synchronized (deque) { if (!deque.peek().equals(current)) { // item got rolled off, try again continue; } // Pull it off the queue and be paranoid. final TaskStatusEvent newCurrent = deque.poll(); count.decrementAndGet(); checkState(current.equals(newCurrent), "current should equal newCurrent"); // Safe because this is the *only* place we hold these two locks at the same time. synchronized (items) { // Extra paranoia: curDeque should always == deque final Deque<TaskStatusEvent> curDeque = items.get(id); if (curDeque != null && curDeque.isEmpty()) { items.remove(id); } } return current; } } }
From source file:de.escalon.hypermedia.spring.hydra.PagedResourcesSerializer.java
protected void serializeContext(Object bean, JsonGenerator jgen, SerializerProvider serializerProvider, Deque<LdContext> contextStack) throws IOException { // TODO: this code is duplicated from JacksonHydraSerializer, see there for considerations if (proxyUnwrapper != null) { bean = proxyUnwrapper.unwrapProxy(bean); }//from w ww . j a v a 2s . com MixinSource mixinSource = new JacksonMixinSource(serializerProvider.getConfig()); final Class<?> mixInClass = mixinSource.findMixInClassFor(bean.getClass()); final LdContext parentContext = contextStack.peek(); LdContext currentContext = new LdContext(parentContext, ldContextFactory.getVocab(mixinSource, bean, mixInClass), ldContextFactory.getTerms(mixinSource, bean, mixInClass)); contextStack.push(currentContext); // check if we need to write a context for the current bean at all // If it is in the same vocab: no context // If the terms are already defined in the context: no context boolean mustWriteContext; if (parentContext == null || !parentContext.contains(currentContext)) { mustWriteContext = true; } else { mustWriteContext = false; } if (mustWriteContext) { // begin context // default context: schema.org vocab or vocab package annotation jgen.writeObjectFieldStart("@context"); // do not repeat vocab if already defined in current context if (parentContext == null || parentContext.vocab == null || (currentContext.vocab != null && !currentContext.vocab.equals(parentContext.vocab))) { jgen.writeStringField(JsonLdKeywords.AT_VOCAB, currentContext.vocab); } for (Map.Entry<String, Object> termEntry : currentContext.terms.entrySet()) { if (termEntry.getValue() instanceof String) { jgen.writeStringField(termEntry.getKey(), termEntry.getValue().toString()); } else { jgen.writeObjectField(termEntry.getKey(), termEntry.getValue()); } } jgen.writeEndObject(); // end context } }
From source file:de.escalon.hypermedia.spring.de.escalon.hypermedia.spring.jackson.LinkListSerializer.java
@Override public void serialize(List<Link> links, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException { try {//from w w w .ja va2 s . c o m Collection<Link> simpleLinks = new ArrayList<Link>(); Collection<Affordance> affordances = new ArrayList<Affordance>(); Collection<Link> templatedLinks = new ArrayList<Link>(); Collection<Affordance> templatedAffordances = new ArrayList<Affordance>(); for (Link link : links) { if (link instanceof Affordance) { final Affordance affordance = (Affordance) link; final List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors(); if (!actionDescriptors.isEmpty()) { if (affordance.isTemplated()) { templatedAffordances.add(affordance); } else { affordances.add(affordance); } } else { if (affordance.isTemplated()) { templatedLinks.add(affordance); } else { simpleLinks.add(affordance); } } } else if (link.isTemplated()) { templatedLinks.add(link); } else { simpleLinks.add(link); } } for (Affordance templatedAffordance : templatedAffordances) { jgen.writeObjectFieldStart(templatedAffordance.getRel()); jgen.writeStringField("@type", "hydra:IriTemplate"); jgen.writeStringField("hydra:template", templatedAffordance.getHref()); final List<ActionDescriptor> actionDescriptors = templatedAffordance.getActionDescriptors(); ActionDescriptor actionDescriptor = actionDescriptors.get(0); jgen.writeArrayFieldStart("hydra:mapping"); writeHydraVariableMapping(jgen, actionDescriptor, actionDescriptor.getPathVariableNames()); writeHydraVariableMapping(jgen, actionDescriptor, actionDescriptor.getRequestParamNames()); jgen.writeEndArray(); jgen.writeEndObject(); } for (Link templatedLink : templatedLinks) { // we only have the template, no access to method params jgen.writeObjectFieldStart(templatedLink.getRel()); jgen.writeStringField("@type", "hydra:IriTemplate"); jgen.writeStringField("hydra:template", templatedLink.getHref()); jgen.writeArrayFieldStart("hydra:mapping"); writeHydraVariableMapping(jgen, null, templatedLink.getVariableNames()); jgen.writeEndArray(); jgen.writeEndObject(); } Deque<String> vocabStack = (Deque<String>) serializerProvider .getAttribute(JacksonHydraSerializer.KEY_LD_CONTEXT); String currentVocab = vocabStack != null ? vocabStack.peek() : null; for (Affordance affordance : affordances) { final String rel = affordance.getRel(); List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors(); if (!actionDescriptors.isEmpty()) { if (!Link.REL_SELF.equals(rel)) { jgen.writeObjectFieldStart(rel); // begin rel } jgen.writeStringField(JacksonHydraSerializer.AT_ID, affordance.getHref()); jgen.writeArrayFieldStart("hydra:operation"); } for (ActionDescriptor actionDescriptor : actionDescriptors) { jgen.writeStartObject(); // begin a hydra:Operation final String semanticActionType = actionDescriptor.getSemanticActionType(); if (semanticActionType != null) { jgen.writeStringField("@type", semanticActionType); } jgen.writeStringField("hydra:method", actionDescriptor.getHttpMethod().name()); final ActionInputParameter requestBodyInputParameter = actionDescriptor.getRequestBody(); if (requestBodyInputParameter != null) { jgen.writeObjectFieldStart("hydra:expects"); // begin hydra:expects final Class<?> clazz = requestBodyInputParameter.getNestedParameterType(); final Expose classExpose = clazz.getAnnotation(Expose.class); final String typeName; if (classExpose != null) { typeName = classExpose.value(); } else { typeName = requestBodyInputParameter.getNestedParameterType().getSimpleName(); } jgen.writeStringField("@type", typeName); jgen.writeArrayFieldStart("hydra:supportedProperty"); // begin hydra:supportedProperty // TODO check need for actionDescriptor and requestBodyInputParameter here: recurseSupportedProperties(jgen, currentVocab, clazz, actionDescriptor, requestBodyInputParameter, requestBodyInputParameter.getCallValue()); jgen.writeEndArray(); // end hydra:supportedProperty jgen.writeEndObject(); // end hydra:expects } jgen.writeEndObject(); // end hydra:Operation } if (!actionDescriptors.isEmpty()) { jgen.writeEndArray(); // end hydra:operation if (!Link.REL_SELF.equals(rel)) { jgen.writeEndObject(); // end rel } } } for (Link simpleLink : simpleLinks) { final String rel = simpleLink.getRel(); if (Link.REL_SELF.equals(rel)) { jgen.writeStringField("@id", simpleLink.getHref()); } else { String linkAttributeName = IanaRels.isIanaRel(rel) ? IANA_REL_PREFIX + rel : rel; jgen.writeObjectFieldStart(linkAttributeName); jgen.writeStringField("@id", simpleLink.getHref()); jgen.writeEndObject(); } } } catch (IntrospectionException e) { throw new RuntimeException(e); } }
From source file:com.streamsets.datacollector.definition.ConfigDefinitionExtractor.java
void resolveDependencies(String configPrefix, List<ConfigDefinition> defs, Object contextMsg) { Map<String, ConfigDefinition> definitionsMap = new HashMap<>(); Map<String, Map<String, Set<Object>>> dependencyMap = new HashMap<>(); Map<String, Boolean> isFullyProcessed = new HashMap<>(); for (ConfigDefinition def : defs) { definitionsMap.put(def.getName(), def); dependencyMap.put(def.getName(), new HashMap<String, Set<Object>>()); isFullyProcessed.put(def.getName(), false); }/*from w w w . j a v a 2 s .c o m*/ cycles.clear(); for (ConfigDefinition def : defs) { String dependsOnKey = def.getDependsOn(); if (!StringUtils.isEmpty(dependsOnKey)) { verifyDependencyExists(definitionsMap, def, dependsOnKey, contextMsg); ConfigDefinition dependsOnDef = definitionsMap.get(dependsOnKey); // evaluate dependsOn triggers ConfigDef annotation = def.getConfigField().getAnnotation(ConfigDef.class); Set<Object> triggers = new HashSet<>(); for (String trigger : annotation.triggeredByValue()) { triggers.add(ConfigValueExtractor.get().extract(dependsOnDef.getConfigField(), dependsOnDef.getType(), trigger, contextMsg, true)); } dependencyMap.get(def.getName()).put(dependsOnDef.getName(), triggers); } // Add direct dependencies to dependencyMap if (!def.getDependsOnMap().isEmpty()) { // Copy same as above. for (Map.Entry<String, List<Object>> dependsOn : def.getDependsOnMap().entrySet()) { dependsOnKey = dependsOn.getKey(); if (!StringUtils.isEmpty(dependsOnKey)) { verifyDependencyExists(definitionsMap, def, dependsOnKey, contextMsg); Set<Object> triggers = new HashSet<>(); ConfigDefinition dependsOnDef = definitionsMap.get(dependsOnKey); for (Object trigger : dependsOn.getValue()) { triggers.add(ConfigValueExtractor.get().extract(dependsOnDef.getConfigField(), dependsOnDef.getType(), (String) trigger, contextMsg, true)); } Map<String, Set<Object>> dependencies = dependencyMap.get(def.getName()); if (dependencies.containsKey(dependsOnKey)) { dependencies.get(dependsOnKey).addAll(triggers); } else { dependencies.put(dependsOnKey, triggers); } } } } } for (ConfigDefinition def : defs) { if (isFullyProcessed.get(def.getName())) { continue; } // Now find all indirect dependencies Deque<StackNode> stack = new ArrayDeque<>(); stack.push(new StackNode(def, new LinkedHashSet<String>())); while (!stack.isEmpty()) { StackNode current = stack.peek(); // We processed this one's dependencies before, don't bother adding its children // The dependencies of this one have all been processed if (current.childrenAddedToStack) { stack.pop(); Map<String, Set<Object>> currentDependencies = dependencyMap.get(current.def.getName()); Set<String> children = new HashSet<>(current.def.getDependsOnMap().keySet()); for (String child : children) { if (StringUtils.isEmpty(child)) { continue; } Map<String, Set<Object>> depsOfChild = dependencyMap.get(child); for (Map.Entry<String, Set<Object>> depOfChild : depsOfChild.entrySet()) { if (currentDependencies.containsKey(depOfChild.getKey())) { // Add only the common trigger values, // since it has to be one of those for both these to be triggered. Set<Object> currentTriggers = currentDependencies.get(depOfChild.getKey()); Set<Object> childTriggers = depOfChild.getValue(); currentDependencies.put(depOfChild.getKey(), Sets.intersection(currentTriggers, childTriggers)); } else { currentDependencies.put(depOfChild.getKey(), new HashSet<>(depOfChild.getValue())); } } } isFullyProcessed.put(current.def.getName(), true); } else { Set<String> children = current.def.getDependsOnMap().keySet(); String dependsOn = current.def.getDependsOn(); LinkedHashSet<String> dependencyAncestors = new LinkedHashSet<>(current.ancestors); dependencyAncestors.add(current.def.getName()); if (!StringUtils.isEmpty(dependsOn) && !isFullyProcessed.get(current.def.getDependsOn()) && !detectCycle(dependencyAncestors, cycles, dependsOn)) { stack.push( new StackNode(definitionsMap.get(current.def.getDependsOn()), dependencyAncestors)); } for (String child : children) { if (!StringUtils.isEmpty(child) && !isFullyProcessed.get(child) && !detectCycle(dependencyAncestors, cycles, child)) { stack.push(new StackNode(definitionsMap.get(child), dependencyAncestors)); } } current.childrenAddedToStack = true; } } } Preconditions.checkState(cycles.isEmpty(), "The following cycles were detected in the configuration dependencies:\n" + Joiner.on("\n").join(cycles)); for (Map.Entry<String, Map<String, Set<Object>>> entry : dependencyMap.entrySet()) { Map<String, List<Object>> dependencies = new HashMap<>(); definitionsMap.get(entry.getKey()).setDependsOnMap(dependencies); for (Map.Entry<String, Set<Object>> trigger : entry.getValue().entrySet()) { List<Object> triggerValues = new ArrayList<>(); triggerValues.addAll(trigger.getValue()); dependencies.put(trigger.getKey(), triggerValues); } definitionsMap.get(entry.getKey()).setDependsOn(""); } }
From source file:RandomChooser.java
private RandomChooser(List<Double> weights, List<T> events, Random random) { double sum = 0.0; for (double prob : weights) sum += prob;/*from w w w. j av a 2s . co m*/ this.probs = new double[weights.size()]; for (int i = 0; i < weights.size(); i++) { probs[i] = weights.get(i) * weights.size() / sum; //average = 1.0 } Deque<Integer> smaller = new ArrayDeque<Integer>(weights.size() / 2 + 2); Deque<Integer> greater = new ArrayDeque<Integer>(weights.size() / 2 + 2); for (int i = 0; i < probs.length; i++) { if (probs[i] < 1.0) { smaller.push(i); } else { greater.push(i); } } indexes = new int[weights.size()]; while (!smaller.isEmpty()) { Integer i = smaller.pop(); Integer k = greater.peek(); indexes[i] = k; probs[k] -= (1 - probs[i]); if (probs[k] < 1.0) { greater.pop(); if (greater.isEmpty()) break; smaller.push(k); } } this.events = events; this.random = random; }
From source file:net.dv8tion.jda.core.entities.impl.ReceivedMessage.java
@Override public String getContentStripped() { if (strippedContent != null) return strippedContent; synchronized (mutex) { if (strippedContent != null) return strippedContent; String tmp = getContentDisplay(); //all the formatting keys to keep track of String[] keys = new String[] { "*", "_", "`", "~~" }; //find all tokens (formatting strings described above) TreeSet<FormatToken> tokens = new TreeSet<>(Comparator.comparingInt(t -> t.start)); for (String key : keys) { Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(tmp); while (matcher.find()) tokens.add(new FormatToken(key, matcher.start())); }/*from w w w . java 2 s .co m*/ //iterate over all tokens, find all matching pairs, and add them to the list toRemove Deque<FormatToken> stack = new ArrayDeque<>(); List<FormatToken> toRemove = new ArrayList<>(); boolean inBlock = false; for (FormatToken token : tokens) { if (stack.isEmpty() || !stack.peek().format.equals(token.format) || stack.peek().start + token.format.length() == token.start) { //we are at opening tag if (!inBlock) { //we are outside of block -> handle normally if (token.format.equals("`")) { //block start... invalidate all previous tags stack.clear(); inBlock = true; } stack.push(token); } else if (token.format.equals("`")) { //we are inside of a block -> handle only block tag stack.push(token); } } else if (!stack.isEmpty()) { //we found a matching close-tag toRemove.add(stack.pop()); toRemove.add(token); if (token.format.equals("`") && stack.isEmpty()) //close tag closed the block inBlock = false; } } //sort tags to remove by their start-index and iteratively build the remaining string toRemove.sort(Comparator.comparingInt(t -> t.start)); StringBuilder out = new StringBuilder(); int currIndex = 0; for (FormatToken formatToken : toRemove) { if (currIndex < formatToken.start) out.append(tmp.substring(currIndex, formatToken.start)); currIndex = formatToken.start + formatToken.format.length(); } if (currIndex < tmp.length()) out.append(tmp.substring(currIndex)); //return the stripped text, escape all remaining formatting characters (did not have matching // open/close before or were left/right of block return strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~"); } }