List of usage examples for java.util SortedMap containsKey
boolean containsKey(Object key);
From source file:net.sourceforge.fenixedu.presentationTier.Action.scientificCouncil.credits.ViewTeacherCreditsReportDispatchAction.java
private void setTotals(HttpServletRequest request, ExecutionYear untilExecutionYear, SortedMap<Department, Map<ExecutionYear, PeriodCreditsReportDTO>> departmentTotalCredits) { int totalTeachersSize = 0, totalCareerTeachersSize = 0, totalNotCareerTeachersSize = 0; SortedMap<ExecutionYear, GenericPair<Double, GenericPair<Double, Double>>> executionYearTotals = new TreeMap<ExecutionYear, GenericPair<Double, GenericPair<Double, Double>>>( ExecutionYear.COMPARATOR_BY_YEAR); for (Department department : departmentTotalCredits.keySet()) { for (ExecutionYear executionYear : departmentTotalCredits.get(department).keySet()) { if (!executionYearTotals.containsKey(executionYear)) { executionYearTotals.put(executionYear, new GenericPair(0.0, new GenericPair(0.0, 0.0))); }/*from w ww.j av a 2 s . c o m*/ GenericPair genericPair = executionYearTotals.get(executionYear); genericPair.setLeft(round(departmentTotalCredits.get(department).get(executionYear).getCredits() + executionYearTotals.get(executionYear).getLeft())); ((GenericPair) genericPair.getRight()).setLeft(round( departmentTotalCredits.get(department).get(executionYear).getCareerCategoryTeacherCredits() + executionYearTotals.get(executionYear).getRight().getLeft())); ((GenericPair) genericPair.getRight()).setRight(round(departmentTotalCredits.get(department) .get(executionYear).getNotCareerCategoryTeacherCredits() + executionYearTotals.get(executionYear).getRight().getRight())); if (executionYear.equals(untilExecutionYear)) { totalTeachersSize += departmentTotalCredits.get(department).get(executionYear) .getTeachersSize(); totalCareerTeachersSize += departmentTotalCredits.get(department).get(executionYear) .getCareerTeachersSize(); totalNotCareerTeachersSize += departmentTotalCredits.get(department).get(executionYear) .getNotCareerTeachersSize(); } } } request.setAttribute("totalCareerTeachersSize", totalCareerTeachersSize); request.setAttribute("totalNotCareerTeachersSize", totalNotCareerTeachersSize); request.setAttribute("totalCareerTeachersBalance", round(executionYearTotals.get(untilExecutionYear).getRight().getLeft() / totalCareerTeachersSize)); request.setAttribute("totalNotCareerTeachersBalance", round( executionYearTotals.get(untilExecutionYear).getRight().getRight() / totalNotCareerTeachersSize)); request.setAttribute("totalBalance", round(executionYearTotals.get(untilExecutionYear).getLeft() / totalTeachersSize)); request.setAttribute("totalTeachersSize", totalTeachersSize); request.setAttribute("executionYearTotals", executionYearTotals); }
From source file:com.alkacon.opencms.counter.CmsCounterDialog.java
/** * This function compares the list from the dialog with the list from the database and * update the list from the database with the values from the dialog.<p> * // ww w .j ava2 s .c o m * @param counterList the list from the dialog * * @throws Exception if an Exception occurred. */ private void updateCounterValues(SortedMap counterList) throws Exception { if (m_manager == null) { m_manager = getCounterManager(); } // get the counters from the database TreeMap map = m_manager.getCounters(); Iterator iteratork = map.keySet().iterator(); Iterator iterator = map.values().iterator(); // for each entry check if its changed or deleted int o_value; int new_value; String o_key; while (iterator.hasNext() && iteratork.hasNext()) { o_value = getIntValue(iterator.next()); o_key = (String) iteratork.next(); if (counterList.containsKey(o_key)) { // the value exits new_value = getIntValue(counterList.get(o_key)); if (o_value != new_value) { if ((o_value < new_value) || (o_value > new_value && m_overwrite)) { m_manager.setCounter(o_key, new_value); } counterList.remove(o_key); } else { counterList.remove(o_key); } } else { // the value is deleted m_manager.deleteCounter(o_key); } } // now the new values is adding to the database if (!counterList.isEmpty()) { iteratork = counterList.keySet().iterator(); iterator = counterList.values().iterator(); while (iterator.hasNext() && iteratork.hasNext()) { o_value = getIntValue(iterator.next()); o_key = (String) iteratork.next(); m_manager.setCounter(o_key, o_value); } } }
From source file:org.bibsonomy.rest.utils.HeaderUtils.java
/** * //from w w w .j ava 2s. co m * @param acceptHeader * the HTML ACCEPT Header * <br/>example: * <code>ACCEPT: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png</code> * would be interpreted in the following precedence: * <ol> * <li>text/xml</li> * <li>image/png</li> * <li>text/html</li> * <li>text/plain</li> * </ol> * ) * @return a sorted map with the precedences */ public static SortedMap<Double, Vector<String>> getPreferredTypes(final String acceptHeader) { // maps the q-value to output format (reverse order) final SortedMap<Double, Vector<String>> preferredTypes = new TreeMap<Double, Vector<String>>( new Comparator<Double>() { @Override public int compare(Double o1, Double o2) { if (o1.doubleValue() > o2.doubleValue()) return -1; else if (o1.doubleValue() < o2.doubleValue()) return 1; else return o1.hashCode() - o2.hashCode(); } }); if (!present(acceptHeader)) { return preferredTypes; } // fill map with q-values and formats final Scanner scanner = new Scanner(acceptHeader.toLowerCase()); scanner.useDelimiter(","); while (scanner.hasNext()) { final String[] types = scanner.next().split(";"); final String type = types[0]; double qValue = 1; if (types.length != 1) { /* * FIXME: we get * java.lang.NumberFormatException: For input string: "screen" * in the error log because the format we assume seems to be * different by some clients. Until we find out, what is really * wrong (our parsing or the client), we are more careful with * parsing external data. */ try { qValue = Double.parseDouble(types[1].split("=")[1]); } catch (NumberFormatException e) { qValue = 0; log.error("Couldn't parse accept header '" + acceptHeader + "'"); } } Vector<String> v = preferredTypes.get(qValue); if (!preferredTypes.containsKey(qValue)) { v = new Vector<String>(); preferredTypes.put(qValue, v); } v.add(type); } return preferredTypes; }
From source file:org.web4thejob.web.util.ToolbarRenderer.java
private SortedMap<CommandEnum, List<Command>> mergeCommands() { SortedMap<CommandEnum, List<Command>> map = new TreeMap<CommandEnum, List<Command>>(COMMANDS_SORTER); for (CommandAware owner : commandOwners) { if (owner instanceof PlaceholderPanel && !owner.equals(getPrimaryOwner())) { continue; }/* w w w. j ava 2 s .c o m*/ SortedSet<Command> commands; if (owner instanceof CommandMerger) { commands = ((CommandMerger) owner).getMergedCommands(); } else { commands = owner.getCommands(); } for (final Command command : commands) { if (isMergable(command)) { if (map.containsKey(command.getId())) { if (!map.get(command.getId()).contains(command)) { map.get(command.getId()).add(command); } } else { List<Command> list = new ArrayList<Command>(); list.add(command); map.put(command.getId(), list); } } } } return map; }
From source file:org.wrml.runtime.DefaultModel.java
@Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { final Context context = getContext(); final SchemaLoader schemaLoader = context.getSchemaLoader(); final Model model = (Model) proxy; final String methodName = method.getName(); final Class<?> modelClass = model.getClass(); final Class<?>[] modelClassInterfaces = modelClass.getInterfaces(); // Get the model class's first implemented interface; it's schema interface final Class<?> modelSchemaInterface = modelClassInterfaces[0]; final URI modelSchemaUri = schemaLoader.getTypeUri(modelSchemaInterface); final Prototype prototype = schemaLoader.getPrototype(modelSchemaUri); // Get the class that defined the invoked method final Class<?> declaringClass = method.getDeclaringClass(); //// w w w .j av a2s .c om // If the invoked method comes from one of the base model types, then it may need to be handled in a // special way. // if (declaringClass.equals(ValueType.JAVA_TYPE_MODEL) || declaringClass.equals(Object.class) || declaringClass.equals(Comparable.class)) { // The invoked method was declared by one of the base model types, it may be a special case method. final SpecialMethod specialMethod = SpecialMethod.fromString(methodName); if (specialMethod != null) { // LOG.debug("Model method: " + method + " is considered a special method."); // The name of the invoked method matches the name of one of our special cases. final int argCount = (args != null) ? args.length : 0; final boolean hasArgs = argCount > 0; final Object firstArg = (hasArgs) ? args[0] : null; switch (specialMethod) { // Handle the special case methods: case clearSlotValue: { if (argCount == 1 && firstArg instanceof String) { final String slotName = (String) firstArg; return clearSlotValue(model, slotName, modelSchemaUri); } break; } case containsSlotValue: { if (argCount == 1 && firstArg instanceof String) { final String slotName = (String) firstArg; return containsSlotValue(model, slotName, modelSchemaUri); } break; } case equals: { if (argCount == 1) { final Object other = firstArg; if (other instanceof Proxy) { return equals(Proxy.getInvocationHandler(other)); } return false; } break; } case getKeys: { if (argCount == 0) { return buildKeys(model); } break; } case getPrototype: { if (argCount == 0) { return prototype; } break; } case getSchemaUri: { if (argCount == 0) { if (ValueType.JAVA_TYPE_MODEL.equals(modelSchemaInterface)) { // Return null (undefined Schema) if we are only a Model return null; } // Reflect back the WRML representation return modelSchemaUri; } break; } case getSlotValue: { if (argCount >= 1) { final String slotName = (String) firstArg; final ProtoSlot protoSlot = prototype.getProtoSlot(slotName); return getSlotValue(model, slotName, protoSlot.getDeclaringSchemaUri()); } break; } case initKeySlots: { if (argCount == 1) { final Keys keys = (Keys) firstArg; initKeySlots(model, keys); return null; } break; } case reference: { if (argCount >= 1) { final String linkSlotName = (String) firstArg; final LinkProtoSlot linkProtoSlot = prototype.getProtoSlot(linkSlotName); Object[] referenceMethodArgs = null; if (argCount > 1) { referenceMethodArgs = ArrayUtils.subarray(args, 1, args.length); } return invokeReference(model, linkProtoSlot, referenceMethodArgs); } break; } case setSlotValue: { if (argCount >= 2) { final String slotName = (String) firstArg; final Object slotValue = args[1]; final ProtoSlot protoSlot = prototype.getProtoSlot(slotName); return setSlotValue(model, slotName, slotValue, protoSlot.getDeclaringSchemaUri()); } break; } default: break; } // End of switch } // LOG.debug("Model method: " + method + " was not handled as a special case."); // Proxy to this RuntimeModel itself, since it is all of the above // declaring classes (independent of Proxy's magic trick). return method.invoke(this, args); } final JavaBean schemaBean = prototype.getSchemaBean(); final SortedMap<String, SortedSet<JavaMethod>> linkMethods = schemaBean.getOtherMethods(); if (linkMethods.containsKey(methodName)) { String linkSlotName = methodName; if (linkSlotName.startsWith(JavaBean.GET)) { linkSlotName = methodName.substring(3); linkSlotName = Character.toLowerCase(linkSlotName.charAt(0)) + linkSlotName.substring(1); } final LinkProtoSlot linkProtoSlot = prototype.getProtoSlot(linkSlotName); DefaultModel.LOG.debug("Model method: " + method + " is considered a link/reference assicuated with slot: " + linkProtoSlot); // The java method's invocation is interpreted as a link reference (i.e. "click"). return invokeReference(model, linkProtoSlot, args); } // // Determine if the method name looks like a slot accessor (setter/getter) meaning that it starts with "get", // "set", or "is". // boolean isWrite = false; String slotName = null; if (methodName.startsWith(JavaBean.GET)) { slotName = methodName.substring(3); } else if (methodName.startsWith(JavaBean.IS)) { slotName = methodName.substring(2); } else if (methodName.startsWith(JavaBean.SET)) { slotName = methodName.substring(3); isWrite = true; } if (slotName != null) { slotName = Character.toLowerCase(slotName.charAt(0)) + slotName.substring(1); final URI declaringSchemaUri = schemaLoader.getTypeUri(declaringClass); if (isWrite) { final Object newSlotValue = args[0]; final Object oldSlotValue = setSlotValue(model, slotName, newSlotValue, declaringSchemaUri); return oldSlotValue; } else { final Object slotValue = getSlotValue(model, slotName, declaringSchemaUri); return slotValue; } } throw new ModelException("Model method invocation was not handled for method: " + method, null, model); }
From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.ViewHomepageDA.java
public ActionForward listStudents(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { final SortedMap<Degree, SortedSet<Homepage>> homepages = new TreeMap<Degree, SortedSet<Homepage>>( Degree.COMPARATOR_BY_DEGREE_TYPE_AND_NAME_AND_ID); for (final Registration registration : rootDomainObject.getRegistrationsSet()) { final StudentCurricularPlan studentCurricularPlan = registration.getActiveStudentCurricularPlan(); if (studentCurricularPlan != null) { final DegreeCurricularPlan degreeCurricularPlan = studentCurricularPlan.getDegreeCurricularPlan(); final Degree degree = degreeCurricularPlan.getDegree(); final Person person = registration.getPerson(); final SortedSet<Homepage> degreeHomepages; if (homepages.containsKey(degree)) { degreeHomepages = homepages.get(degree); } else { degreeHomepages = new TreeSet<Homepage>(Homepage.HOMEPAGE_COMPARATOR_BY_NAME); homepages.put(degree, degreeHomepages); }/*from ww w. j a v a2s . c o m*/ final Homepage homepage = person.getHomepage(); if (homepage != null && homepage.getActivated().booleanValue()) { degreeHomepages.add(homepage); } } } request.setAttribute("homepages", homepages); final String selectedPage = request.getParameter("selectedPage"); if (selectedPage != null) { request.setAttribute("selectedPage", selectedPage); } return mapping.findForward("list-homepages-students"); }
From source file:org.apereo.portal.portlets.search.SearchPortletController.java
private SortedMap<Integer, List<AutocompleteResultsModel>> createAutocompletePriorityMap() { SortedMap<Integer, List<AutocompleteResultsModel>> resultsMap = new TreeMap<Integer, List<AutocompleteResultsModel>>(); for (Map.Entry<String, Integer> entry : autocompleteResultTypeToPriorityMap.entrySet()) { if (!resultsMap.containsKey(entry.getValue())) { resultsMap.put(entry.getValue(), new ArrayList<AutocompleteResultsModel>()); }/*w w w .j av a 2s . com*/ } // Insure there is always a default entry of priority 0. resultsMap.put(0, new ArrayList<AutocompleteResultsModel>()); return resultsMap; }
From source file:com.uber.jenkins.phabricator.coverage.CoberturaXMLParser.java
private Map<String, List<Integer>> parse(Map<NodeList, List<String>> coverageData) { Map<String, SortedMap<Integer, Integer>> internalCounts = new HashMap<String, SortedMap<Integer, Integer>>(); // Each entry in the map is an XML list of classes (files) mapped to its possible source roots for (Map.Entry<NodeList, List<String>> entry : coverageData.entrySet()) { NodeList classes = entry.getKey(); List<String> sourceDirs = entry.getValue(); // Loop over all files in the coverage report for (int i = 0; i < classes.getLength(); i++) { Node classNode = classes.item(i); String fileName = classNode.getAttributes().getNamedItem(NODE_FILENAME).getTextContent(); if (includeFileNames != null && !includeFileNames.contains(FilenameUtils.getName(fileName))) { continue; }//w w w. j ava 2 s . com // Make a guess on which of the `sourceDirs` contains the file in question String detectedSourceRoot = new PathResolver(workspace, sourceDirs).choose(fileName); fileName = join(detectedSourceRoot, fileName); SortedMap<Integer, Integer> hitCounts = internalCounts.get(fileName); if (hitCounts == null) { hitCounts = new TreeMap<Integer, Integer>(); } NodeList children = classNode.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node child = children.item(j); if (NODE_NAME_LINES.equals(child.getNodeName())) { NodeList lines = child.getChildNodes(); for (int k = 0; k < lines.getLength(); k++) { Node line = lines.item(k); if (!NODE_NAME_LINE.equals(line.getNodeName())) { continue; } Integer lineNumber = getIntValue(line, NODE_NUMBER); int existingHits = hitCounts.containsKey(lineNumber) ? hitCounts.get(lineNumber) : 0; hitCounts.put(lineNumber, Math.max(existingHits, getIntValue(line, NODE_HITS))); } internalCounts.put(fileName, hitCounts); } } } } return computeLineCoverage(internalCounts); }
From source file:io.prestosql.execution.resourceGroups.TestResourceGroups.java
@Test(timeOut = 10_000) public void testPriorityScheduling() { RootInternalResourceGroup root = new RootInternalResourceGroup("root", (group, export) -> { }, directExecutor());/* w w w . j a va 2 s .c o m*/ root.setSoftMemoryLimit(new DataSize(1, MEGABYTE)); root.setMaxQueuedQueries(100); // Start with zero capacity, so that nothing starts running until we've added all the queries root.setHardConcurrencyLimit(0); root.setSchedulingPolicy(QUERY_PRIORITY); InternalResourceGroup group1 = root.getOrCreateSubGroup("1"); group1.setSoftMemoryLimit(new DataSize(1, MEGABYTE)); group1.setMaxQueuedQueries(100); group1.setHardConcurrencyLimit(1); InternalResourceGroup group2 = root.getOrCreateSubGroup("2"); group2.setSoftMemoryLimit(new DataSize(1, MEGABYTE)); group2.setMaxQueuedQueries(100); group2.setHardConcurrencyLimit(1); SortedMap<Integer, MockQueryExecution> queries = new TreeMap<>(); Random random = new Random(); for (int i = 0; i < 100; i++) { int priority; do { priority = random.nextInt(1_000_000) + 1; } while (queries.containsKey(priority)); MockQueryExecution query = new MockQueryExecution(0, "query_id", priority); if (random.nextBoolean()) { group1.run(query); } else { group2.run(query); } queries.put(priority, query); } root.setHardConcurrencyLimit(1); List<MockQueryExecution> orderedQueries = new ArrayList<>(queries.values()); reverse(orderedQueries); for (MockQueryExecution query : orderedQueries) { root.processQueuedQueries(); assertEquals(query.getState(), RUNNING); query.complete(); } }
From source file:com.emc.vipr.services.s3.ViPRS3Signer.java
/** * Calculate the canonical string for a REST/HTTP request to S3. * <p/>//from w w w . j a v a2s . c o m * When expires is non-null, it will be used instead of the Date header. */ protected String makeS3CanonicalString(String method, String resource, Request<?> request, String expires) { StringBuilder buf = new StringBuilder(); buf.append(method).append("\n"); // Add all interesting headers to a list, then sort them. "Interesting" // is defined as Content-MD5, Content-Type, Date, and x-amz- and x-emc- Map<String, String> headersMap = request.getHeaders(); SortedMap<String, String> interestingHeaders = new TreeMap<String, String>(); if (headersMap != null && headersMap.size() > 0) { for (Map.Entry<String, String> entry : headersMap.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key == null) continue; String lk = key.toLowerCase(Locale.getDefault()); // Ignore any headers that are not particularly interesting. if (lk.equals("content-type") || lk.equals("content-md5") || lk.equals("date") || lk.startsWith(Headers.AMAZON_PREFIX) || lk.startsWith(ViPRConstants.EMC_PREFIX)) { interestingHeaders.put(lk, value); } } } // Remove default date timestamp if "x-amz-date" is set. if (interestingHeaders.containsKey(Headers.S3_ALTERNATE_DATE)) { interestingHeaders.put("date", ""); } // Use the expires value as the timestamp if it is available. This trumps both the default // "date" timestamp, and the "x-amz-date" header. if (expires != null) { interestingHeaders.put("date", expires); } // These headers require that we still put a new line in after them, // even if they don't exist. if (!interestingHeaders.containsKey("content-type")) { interestingHeaders.put("content-type", ""); } if (!interestingHeaders.containsKey("content-md5")) { interestingHeaders.put("content-md5", ""); } // Any parameters that are prefixed with "x-amz-" need to be included // in the headers section of the canonical string to sign for (Map.Entry<String, String> parameter : request.getParameters().entrySet()) { if (parameter.getKey().startsWith("x-amz-")) { interestingHeaders.put(parameter.getKey(), parameter.getValue()); } } // Add all the interesting headers (i.e.: all that startwith x-amz- or x-emc- ;-)) for (Map.Entry<String, String> entry : interestingHeaders.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key.startsWith(Headers.AMAZON_PREFIX) || key.startsWith(ViPRConstants.EMC_PREFIX)) { buf.append(key).append(':').append(value); } else { buf.append(value); } buf.append("\n"); } // Add all the interesting parameters buf.append(resource); String[] parameterNames = request.getParameters().keySet() .toArray(new String[request.getParameters().size()]); Arrays.sort(parameterNames); char separator = '?'; for (String parameterName : parameterNames) { // Skip any parameters that aren't part of the canonical signed string if (!SIGNED_PARAMETERS.contains(parameterName)) continue; buf.append(separator); buf.append(parameterName); String parameterValue = request.getParameters().get(parameterName); if (parameterValue != null) { buf.append("=").append(parameterValue); } separator = '&'; } return buf.toString(); }