List of usage examples for java.util SortedMap keySet
Set<K> keySet();
From source file:org.opennaas.extensions.genericnetwork.test.capability.circuitstatistics.CircuitStatisticsCapabilityTest.java
@Test @SuppressWarnings("unchecked") public void filterByTimePeriodTest() throws SecurityException, IllegalArgumentException, IllegalAccessException, CapabilityException, NoSuchMethodException, InvocationTargetException { GenericNetworkModel model = new GenericNetworkModel(); SortedMap<Long, List<CircuitStatistics>> circuitStatistics = new TreeMap<Long, List<CircuitStatistics>>(); circuitStatistics.put(FIRST_TIMESTAMP, Arrays.asList(firstStatistics, secondStatistics)); circuitStatistics.put(SECOND_TIMESTAMP, Arrays.asList(thirdStatistics)); model.setCircuitStatistics(circuitStatistics); IResource resource = new Resource(); resource.setModel(model);/*ww w . j a v a2 s . c o m*/ injectPrivateField(circuitStatisticsCapab, resource, "resource"); TimePeriod timePeriod = new TimePeriod(FIRST_TIMESTAMP - 2L, FIRST_TIMESTAMP - 1L); String statisticsInCSV = circuitStatisticsCapab.getStatistics(timePeriod); Assert.assertTrue("Capability should not contain any statistic for this time period", statisticsInCSV.isEmpty()); timePeriod = new TimePeriod(SECOND_TIMESTAMP + 1L, SECOND_TIMESTAMP + 2L); statisticsInCSV = circuitStatisticsCapab.getStatistics(timePeriod); Assert.assertTrue("Capability should not contain any statistic for this time period", statisticsInCSV.isEmpty()); timePeriod = new TimePeriod(FIRST_TIMESTAMP, SECOND_TIMESTAMP - 1L); statisticsInCSV = circuitStatisticsCapab.getStatistics(timePeriod); Assert.assertFalse("Capability should contain statistics for this time period", statisticsInCSV.isEmpty()); // call private method by reflection in order to parse CSV and make assertions Method method = circuitStatisticsCapab.getClass().getDeclaredMethod("parseCSV", String.class); method.setAccessible(true); SortedMap<Long, List<CircuitStatistics>> statistics = (SortedMap<Long, List<CircuitStatistics>>) method .invoke(circuitStatisticsCapab, statisticsInCSV); Assert.assertEquals("There's only one timestamp between this period of time", 1, statistics.keySet().size()); Assert.assertNotNull("There should be statistics between this period of time.", statistics.get(FIRST_TIMESTAMP)); Assert.assertEquals("There should be two statistics between this period of time.", 2, statistics.get(FIRST_TIMESTAMP).size()); Assert.assertEquals(statistics.get(FIRST_TIMESTAMP).get(0), firstStatistics); Assert.assertEquals(statistics.get(FIRST_TIMESTAMP).get(1), secondStatistics); timePeriod = new TimePeriod(SECOND_TIMESTAMP - 1L, SECOND_TIMESTAMP); statisticsInCSV = circuitStatisticsCapab.getStatistics(timePeriod); Assert.assertFalse("Capability should contain statistics for this time period", statisticsInCSV.isEmpty()); // call private method by reflection in order to parse CSV and make assertions method = circuitStatisticsCapab.getClass().getDeclaredMethod("parseCSV", String.class); method.setAccessible(true); statistics = (SortedMap<Long, List<CircuitStatistics>>) method.invoke(circuitStatisticsCapab, statisticsInCSV); Assert.assertEquals("There's only one timestamp between this period of time", 1, statistics.keySet().size()); Assert.assertNotNull("There should be statistics between this period of time.", statistics.get(SECOND_TIMESTAMP)); Assert.assertEquals("There should be one statistic between this period of time.", 1, statistics.get(SECOND_TIMESTAMP).size()); Assert.assertEquals(statistics.get(SECOND_TIMESTAMP).get(0), thirdStatistics); }
From source file:fr.aliasource.webmail.proxy.impl.ResponderImpl.java
public void sendSummary(SortedMap<IFolder, Integer> summary) { try {/* w ww .ja va 2s. co m*/ Document doc = DOMUtils.createDoc("http://obm.aliasource.fr/xsd/folder_list", "folderList"); Element root = doc.getDocumentElement(); for (IFolder f : summary.keySet()) { Element fe = DOMUtils.createElement(root, "folder"); fe.setAttribute("displayName", f.getDisplayName()); fe.setAttribute("name", f.getName()); fe.setAttribute("unread", summary.get(f).toString()); } sendDom(doc); } catch (Exception e) { logger.error(e.getMessage(), e); } }
From source file:se.tillvaxtverket.ttsigvalws.ttwebservice.TTSigValServlet.java
private void checkEncoding(byte[] attrBytes) { SortedMap<String, Charset> availableCharsets = Charset.availableCharsets(); Set<String> keySet = availableCharsets.keySet(); List<String> charsets = new ArrayList<String>(); List<String> decoded = new ArrayList<String>(); for (String key : keySet) { Charset cs = availableCharsets.get(key); charsets.add(key);/*www .jav a2 s. c om*/ decoded.add(new String(attrBytes, cs)); } int i = 0; }
From source file:playground.sergioo.workplaceCapacities2012.MainWorkplaceCapacities.java
private static Map<String, PointPerson> getWorkActivityTimes() throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException, NoConnectionException { DataBaseAdmin dataBaseHits = new DataBaseAdmin(new File("./data/hits/DataBase.properties")); Map<String, PersonSchedule> times; ResultSet timesResult = dataBaseHits.executeQuery( "SELECT pax_idx,trip_id,t6_purpose,t3_starttime,t4_endtime,p6_occup,t5_placetype FROM hits.hitsshort"); times = new HashMap<String, PersonSchedule>(); while (timesResult.next()) { PersonSchedule timesPerson = times.get(timesResult.getString(1)); if (timesPerson == null) { timesPerson = new PersonSchedule(timesResult.getString(1), timesResult.getString(6)); times.put(timesResult.getString(1), timesPerson); }//from ww w .j a va 2s . c o m if (timesResult.getInt(2) != 0) { Iterator<Entry<Integer, Trip>> timesPersonI = timesPerson.getTrips().entrySet().iterator(); Entry<Integer, Trip> last = null; while (timesPersonI.hasNext()) last = timesPersonI.next(); if (last == null || last.getKey() != timesResult.getInt(2)) { int startTime = (timesResult.getInt(4) % 100) * 60 + (timesResult.getInt(4) / 100) * 3600; int endTime = (timesResult.getInt(5) % 100) * 60 + (timesResult.getInt(5) / 100) * 3600; if (last != null && last.getKey() < timesResult.getInt(2) && last.getValue().getEndTime() > startTime) { startTime += 12 * 3600; endTime += 12 * 3600; } if (last != null && last.getKey() < timesResult.getInt(2) && last.getValue().getEndTime() > startTime) { startTime += 12 * 3600; endTime += 12 * 3600; } timesPerson.getTrips().put(timesResult.getInt(2), new Trip(timesResult.getString(3), startTime, endTime, timesResult.getString(7))); } } } timesResult.close(); Map<String, PointPerson> points = new HashMap<String, PointPerson>(); for (PersonSchedule timesPerson : times.values()) { SortedMap<Integer, Trip> tripsPerson = timesPerson.getTrips(); boolean startTimeSaved = false; double startTime = -1, endTime = -1; String placeType = null; if (tripsPerson.size() > 0) { for (int i = tripsPerson.keySet().iterator().next(); i <= tripsPerson.size(); i++) { if (!startTimeSaved && tripsPerson.get(i).getPurpose() != null && tripsPerson.get(i).getPurpose().equals("work")) { startTime = tripsPerson.get(i).getEndTime(); startTimeSaved = true; } if (i > tripsPerson.keySet().iterator().next() && tripsPerson.get(i - 1).getPurpose().equals("work")) { endTime = tripsPerson.get(i).getStartTime(); placeType = tripsPerson.get(i - 1).getPlaceType(); } } } if (startTime != -1 && endTime != -1 && endTime - startTime >= 7 * 3600 && endTime - startTime <= 16 * 3600) if (startTime > 24 * 3600) points.put(timesPerson.getId(), new PointPerson( timesPerson.getId(), timesPerson.getOccupation(), new Double[] { startTime - 24 * 3600, endTime - 24 * 3600 - (startTime - 24 * 3600) }, placeType)); else points.put(timesPerson.getId(), new PointPerson(timesPerson.getId(), timesPerson.getOccupation(), new Double[] { startTime, endTime - startTime }, placeType)); } Map<String, Double> weights; try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(WEIGHTS2_MAP_FILE)); weights = (Map<String, Double>) ois.readObject(); ois.close(); } catch (EOFException e) { weights = new HashMap<String, Double>(); ResultSet weightsR = dataBaseHits.executeQuery("SELECT pax_idx,hipf10 FROM hits.hitsshort_geo_hipf"); while (weightsR.next()) weights.put(weightsR.getString(1), weightsR.getDouble(2)); for (PointPerson pointPerson : points.values()) { if (weights.get(pointPerson.getId()) != null) pointPerson.setWeight(weights.get(pointPerson.getId())); else pointPerson.setWeight(100); } ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(WEIGHTS2_MAP_FILE)); oos.writeObject(weights); oos.close(); } dataBaseHits.close(); return points; }
From source file:org.kuali.kra.budget.external.budget.impl.BudgetAdjustmentServiceHelperImpl.java
public SortedMap<RateType, ScaleTwoDecimal> getNonPersonnelCalculatedDirectCost(Budget currentBudget, AwardBudgetExt previousBudget) { SortedMap<RateType, List<ScaleTwoDecimal>> currentNonPersonnelCalcDirectCost = currentBudget .getNonPersonnelCalculatedExpenseTotals(); SortedMap<RateType, ScaleTwoDecimal> netNonPersonnelCalculatedDirectCost = new TreeMap<RateType, ScaleTwoDecimal>(); int period = currentBudget.getBudgetPeriods().size() - 1; for (RateType rateType : currentNonPersonnelCalcDirectCost.keySet()) { List<ScaleTwoDecimal> currentExpenses = currentNonPersonnelCalcDirectCost.get(rateType); netNonPersonnelCalculatedDirectCost.put(rateType, currentExpenses.get(period)); }//from w w w .ja va 2 s. c o m return netNonPersonnelCalculatedDirectCost; }
From source file:org.gvnix.web.screen.roo.addon.RelatedPatternMetadataProvider.java
/** * Get master entity./* w w w. j a va2 s . c o m*/ * * @param entity Current entity (entity placed into detail on pattern) * @param relatedEntities Related entities * @return Master entity */ protected JavaType getMasterEntity(JavaType entity, SortedMap<JavaType, JavaTypeMetadataDetails> relatedEntities) { try { // The other related entity is the master entity // TODO Can be more related entities besides master entity SortedMap<JavaType, JavaTypeMetadataDetails> tempMap = new TreeMap<JavaType, JavaTypeMetadataDetails>( relatedEntities); tempMap.remove(entity); ClassOrInterfaceTypeDetails cid = null; Set<JavaType> keySet = tempMap.keySet(); Iterator<JavaType> it = keySet.iterator(); while (it.hasNext()) { JavaType type = it.next(); cid = getTypeLocationService().getTypeDetails(type); if (!cid.getEnumConstants().isEmpty()) { tempMap.remove(type); } } return tempMap.lastKey(); } catch (NoSuchElementException e) { LOGGER.fine(String.format("Related pattern without master entity (%s)", entity)); // This is a related pattern without master entity. Is this possible // ? } return null; }
From source file:org.openehr.rm.binding.DADLBinding.java
public List<String> toDADL(Object obj, int indent, List<String> lines) throws Exception { log.debug("toDADL on obj.getClass: " + obj.getClass().getCanonicalName() + ", indent: " + indent + ", line.size: " + lines.size()); Class klass = obj.getClass(); String className = klass.getSimpleName(); String rmName = toUnderscoreSeparated(className).toUpperCase(); String typeHeader = "(" + rmName + ") <"; int size = lines.size(); if (size == 0) { lines.add(typeHeader);//from w w w . j a v a 2 s.c om } else { String l = lines.get(size - 1); l += typeHeader; lines.set(size - 1, l); } SortedMap<String, Attribute> attributes = attributeMap(obj.getClass()); String name = null; Object value = null; StringBuffer buf = null; for (Iterator<String> names = attributes.keySet().iterator(); names.hasNext();) { name = names.next(); Attribute attribute = attributes.get(name); if (attribute.system()) { continue; } if ("parent".equals(attribute.name())) { continue; // causing dead-loops } Method getter = getter(name, obj.getClass()); if (getter != null) { value = getter.invoke(obj, null); buf = new StringBuffer(); if (value != null) { for (int i = 0; i < indent; i++) { buf.append("\t"); } buf.append(toUnderscoreSeparated(name)); buf.append(" = "); if (isOpenEHRRMClass(value) && !(value instanceof ProportionKind)) { lines.add(buf.toString()); log.debug("fetching attribute: " + name); toDADL(value, indent + 1, lines); } else if (value instanceof List) { buf.append("<"); lines.add(buf.toString()); List list = (List) value; for (int i = 0, j = list.size(); i < j; i++) { buf = new StringBuffer(); for (int k = 0; k < indent + 1; k++) { buf.append("\t"); } lines.add(buf.toString() + "[" + (i + 1) + "] = "); toDADL(list.get(i), indent + 2, lines); } buf = new StringBuffer(); for (int i = 0; i < indent; i++) { buf.append("\t"); } buf.append(">"); lines.add(buf.toString()); } else { buf.append("<"); if (value instanceof String || value instanceof Boolean) { buf.append("\""); buf.append(value); buf.append("\""); } else { buf.append(value.toString()); } buf.append(">"); lines.add(buf.toString()); } } } } buf = new StringBuffer(); for (int i = 0; i < indent - 1; i++) { buf.append("\t"); } buf.append(">"); lines.add(buf.toString()); return lines; }
From source file:com.baidubce.auth.BceV1Signer.java
/** * Sign the given request with the given set of credentials. Modifies the passed-in request to apply the signature. * * @param request the request to sign. * @param credentials the credentials to sign the request with. * @param options the options for signing. *//* w w w .ja v a 2 s . c o m*/ @Override public void sign(InternalRequest request, BceCredentials credentials, SignOptions options) { checkNotNull(request, "request should not be null."); if (credentials == null) { return; } if (options == null) { if (request.getSignOptions() != null) { options = request.getSignOptions(); } else { options = SignOptions.DEFAULT; } } String accessKeyId = credentials.getAccessKeyId(); String secretAccessKey = credentials.getSecretKey(); request.addHeader(Headers.HOST, HttpUtils.generateHostHeader(request.getUri())); if (credentials instanceof BceSessionCredentials) { request.addHeader(Headers.BCE_SECURE_TOKEN, ((BceSessionCredentials) credentials).getSessionToken()); } Date timestamp = options.getTimestamp(); if (timestamp == null) { timestamp = new Date(); } String authString = BceV1Signer.BCE_AUTH_VERSION + "/" + accessKeyId + "/" + DateUtils.formatAlternateIso8601Date(timestamp) + "/" + options.getExpirationInSeconds(); String signingKey = this.sha256Hex(secretAccessKey, authString); // Formatting the URL with signing protocol. String canonicalURI = this.getCanonicalURIPath(request.getUri().getPath()); // Formatting the query string with signing protocol. String canonicalQueryString = HttpUtils.getCanonicalQueryString(request.getParameters(), true); // Sorted the headers should be signed from the request. SortedMap<String, String> headersToSign = this.getHeadersToSign(request.getHeaders(), options.getHeadersToSign()); // Formatting the headers from the request based on signing protocol. String canonicalHeader = this.getCanonicalHeaders(headersToSign); String signedHeaders = ""; if (options.getHeadersToSign() != null) { signedHeaders = BceV1Signer.signedHeaderStringJoiner.join(headersToSign.keySet()); signedHeaders = signedHeaders.trim().toLowerCase(); } String canonicalRequest = request.getHttpMethod() + "\n" + canonicalURI + "\n" + canonicalQueryString + "\n" + canonicalHeader; // Signing the canonical request using key with sha-256 algorithm. String signature = this.sha256Hex(signingKey, canonicalRequest); String authorizationHeader = authString + "/" + signedHeaders + "/" + signature; logger.debug("CanonicalRequest:{}\tAuthorization:{}", canonicalRequest.replace("\n", "[\\n]"), authorizationHeader); request.addHeader(Headers.AUTHORIZATION, authorizationHeader); }
From source file:de.pixida.logtest.designer.logreader.LogReaderEditor.java
private List<Triple<String, Node, String>> createConfigurationForm() { final List<Triple<String, Node, String>> formItems = new ArrayList<>(); // Headline pattern final TextField textInput = new TextField(this.logReader.getHeadlinePattern()); textInput.textProperty().addListener((ChangeListener<String>) (observable, oldValue, newValue) -> { this.logReader.setHeadlinePattern(newValue); this.setChanged(true); });//from ww w. j a v a 2 s.c o m textInput.setStyle("-fx-font-family: monospace"); formItems.add(Triple.of("Headline Pattern", textInput, "The perl style regular expression is used to spot the beginning of" + " log entries in the log file. If a log entry consists of multiple lines, this pattern must only match the first" + " line, called \"head line\". Groups can intentionally be matched to spot values like timestamp or channel name." + " All matching groups are removed from the payload before they are processed by an automaton.")); // Index of timestamp Supplier<Integer> getter = () -> this.logReader.getHeadlinePatternIndexOfTimestamp(); Consumer<Integer> setter = value -> this.logReader.setHeadlinePatternIndexOfTimestamp(value); final TextField indexOfTimestampInput = this.createIntegerInputField(textInput, getter, setter); formItems.add(Triple.of("Timestamp Group", indexOfTimestampInput, "Denotes which matching group in the headline pattern contains" + " the timestamp. Index 0 references the whole pattern match, index 1 is the first matching group etc. The timestamp must" + " always be a valid integer. Currently, this integer is always interpreted as milliseconds. If no value is set, no" + " timestamp will be extracted and timing conditions cannot be used. If the referenced matching group is optional" + " and does not match for a specific head line, the last recent timestamp will be used for the extracted log entry.")); // Index of channel getter = () -> this.logReader.getHeadlinePatternIndexOfChannel(); setter = value -> this.logReader.setHeadlinePatternIndexOfChannel(value); final TextField indexOfChannelInput = this.createIntegerInputField(textInput, getter, setter); formItems.add(Triple.of("Channel Group", indexOfChannelInput, "Denotes which matching group in the headline pattern contains" + " the channel. If the value is empty or the matching group is optional and it did not match, the default channel is used" + " for the extracted log entry.")); // Trim payload CheckBox cb = new CheckBox(); cb.setSelected(this.logReader.getTrimPayload()); cb.selectedProperty().addListener((ChangeListener<Boolean>) (observable, oldValue, newValue) -> { this.logReader.setTrimPayload(BooleanUtils.toBoolean(newValue)); this.setChanged(true); }); formItems.add(Triple.of("Trim Payload", cb, "Only has effect on multiline payloads." + " If enabled, all leading and trailing whitespaces are removed from the payload" + " after the matching groups are removed. This allows for regular expressions in the automaton that match the beginning" + " and the end of the payload, without having to take care too much for whitespaces in the source log file.")); // Handling of non headline lines this.createInputForHandlingOfNonHeadlineLines(formItems); // Trim payload cb = new CheckBox(); cb.setSelected(this.logReader.getRemoveEmptyPayloadLinesFromMultilineEntry()); cb.selectedProperty().addListener((ChangeListener<Boolean>) (observable, oldValue, newValue) -> { this.logReader.setRemoveEmptyPayloadLinesFromMultilineEntry(BooleanUtils.toBoolean(newValue)); this.setChanged(true); }); formItems.add(Triple.of("Remove Empty Lines", cb, "If enabled, empty lines will be removed from multiline payload entries.")); // Charset final SortedMap<String, Charset> charsets = Charset.availableCharsets(); final ChoiceBox<String> encodingInput = new ChoiceBox<>( FXCollections.observableArrayList(charsets.keySet())); encodingInput.getSelectionModel().select(this.logReader.getLogFileCharset().name()); encodingInput.getSelectionModel().selectedItemProperty() .addListener((ChangeListener<String>) (observable, oldValue, newValue) -> { this.logReader.setLogFileCharset(charsets.get(newValue)); this.setChanged(true); }); formItems.add(Triple.of("Log File Encoding", encodingInput, "Encoding of the log file. Note that some of the encodings are" + " platform specific such that reading the log on a different platform might fail. Usually, log files are written" + " using UTF-8, UTF-16, ISO-8859-1 or ASCII.")); return formItems; }
From source file:com.android.build.gradle.internal.pipeline.InjectTransformManager.java
/** * ??Transform?Transform?//from ww w .ja v a 2 s. c om * * @param transformClazz * @param injectTransform * @param scope * @param <T> * @return */ public <T extends InjectTransform> TransformTask addInjectTransformBeforeTransform( Class<? extends Transform> transformClazz, T injectTransform, @NonNull VariantScope scope) { TaskCollection<DefaultAndroidTask> androidTasks = project.getTasks().withType(DefaultAndroidTask.class); SortedMap<String, DefaultAndroidTask> androidTaskSortedMap = androidTasks.getAsMap(); TransformTask oprTransformTask = null; // ?? for (String taskName : androidTaskSortedMap.keySet()) { DefaultAndroidTask androidTask = androidTaskSortedMap.get(taskName); if (variantName.equals(androidTask.getVariantName())) { if (androidTask instanceof TransformTask && ((TransformTask) androidTask).getTransform().getClass().equals(transformClazz)) { oprTransformTask = (TransformTask) androidTask; break; } } } if (null == oprTransformTask) { throw new StopExecutionException( "TransformTask with transfrom type:" + transformClazz.getName() + " can not found!"); } transforms.add(injectTransform); //2Transform??,?typetype checkTransformConfig(oprTransformTask.getTransform(), injectTransform); String taskName = scope.getTaskName(getTaskNamePrefix(injectTransform)); try { IntermediateStream outputStream = getOutputStream(injectTransform, scope, taskName); // ?TransformTask TransformTaskParam transformTaskParam = getTransformParam(oprTransformTask); TransformTask.ConfigAction<T> configAction = new TransformTask.ConfigAction<T>(variantName, taskName, injectTransform, transformTaskParam.consumedInputStreams, transformTaskParam.referencedInputStreams, outputStream, ThreadRecorder.get(), null); TransformTask injectTransformTask = project.getTasks().create(configAction.getName(), configAction.getType()); oprTransformTask.dependsOn(injectTransformTask); for (TransformStream transformStream : transformTaskParam.consumedInputStreams) { if (null != transformStream.getDependencies()) { injectTransformTask.dependsOn(transformStream.getDependencies()); } } for (TransformStream transformStream : transformTaskParam.referencedInputStreams) { if (null != transformStream.getDependencies()) { injectTransformTask.dependsOn(transformStream.getDependencies()); } } if (transformTaskList.size() > 0) { injectTransformTask.dependsOn(transformTaskList.get(transformTaskList.size() - 1)); } transformTaskList.add(taskName); configAction.execute(injectTransformTask); //oprTransformTask if (injectTransform.updateNextTransformInput()) { Collection<TransformStream> newInputStream = Lists.newArrayList(); newInputStream.add(outputStream); updateTransformTaskConfig(oprTransformTask, newInputStream, transformTaskParam.referencedInputStreams, transformTaskParam.outputStream); } return injectTransformTask; } catch (IllegalAccessException e) { throw new StopExecutionException(e.getMessage()); } }