List of usage examples for java.util TreeMap entrySet
EntrySet entrySet
To view the source code for java.util TreeMap entrySet.
Click Source Link
From source file:ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition.java
@SuppressWarnings("unchecked") private void scanCompositeElementForChildren(Set<String> elementNames, TreeMap<Integer, BaseRuntimeDeclaredChildDefinition> theOrderToElementDef, TreeMap<Integer, BaseRuntimeDeclaredChildDefinition> theOrderToExtensionDef) { int baseElementOrder = 0; for (ScannedField next : myScannedFields) { if (next.isFirstFieldInNewClass()) { baseElementOrder = theOrderToElementDef.isEmpty() ? 0 : theOrderToElementDef.lastEntry().getKey() + 1; }/*from w w w . j a v a2s . co m*/ Class<?> declaringClass = next.getField().getDeclaringClass(); Description descriptionAnnotation = ModelScanner.pullAnnotation(next.getField(), Description.class); TreeMap<Integer, BaseRuntimeDeclaredChildDefinition> orderMap = theOrderToElementDef; Extension extensionAttr = ModelScanner.pullAnnotation(next.getField(), Extension.class); if (extensionAttr != null) { orderMap = theOrderToExtensionDef; } Child childAnnotation = next.getChildAnnotation(); Field nextField = next.getField(); String elementName = childAnnotation.name(); int order = childAnnotation.order(); boolean childIsChoiceType = false; boolean orderIsReplaceParent = false; if (order == Child.REPLACE_PARENT) { if (extensionAttr != null) { for (Entry<Integer, BaseRuntimeDeclaredChildDefinition> nextEntry : orderMap.entrySet()) { BaseRuntimeDeclaredChildDefinition nextDef = nextEntry.getValue(); if (nextDef instanceof RuntimeChildDeclaredExtensionDefinition) { if (nextDef.getExtensionUrl().equals(extensionAttr.url())) { orderIsReplaceParent = true; order = nextEntry.getKey(); orderMap.remove(nextEntry.getKey()); elementNames.remove(elementName); break; } } } if (order == Child.REPLACE_PARENT) { throw new ConfigurationException("Field " + nextField.getName() + "' on target type " + declaringClass.getSimpleName() + " has order() of REPLACE_PARENT (" + Child.REPLACE_PARENT + ") but no parent element with extension URL " + extensionAttr.url() + " could be found on type " + nextField.getDeclaringClass().getSimpleName()); } } else { for (Entry<Integer, BaseRuntimeDeclaredChildDefinition> nextEntry : orderMap.entrySet()) { BaseRuntimeDeclaredChildDefinition nextDef = nextEntry.getValue(); if (elementName.equals(nextDef.getElementName())) { orderIsReplaceParent = true; order = nextEntry.getKey(); BaseRuntimeDeclaredChildDefinition existing = orderMap.remove(nextEntry.getKey()); elementNames.remove(elementName); /* * See #350 - If the original field (in the superclass) with the given name is a choice, then we need to make sure * that the field which replaces is a choice even if it's only a choice of one type - this is because the * element name when serialized still needs to reflect the datatype */ if (existing instanceof RuntimeChildChoiceDefinition) { childIsChoiceType = true; } break; } } if (order == Child.REPLACE_PARENT) { throw new ConfigurationException("Field " + nextField.getName() + "' on target type " + declaringClass.getSimpleName() + " has order() of REPLACE_PARENT (" + Child.REPLACE_PARENT + ") but no parent element with name " + elementName + " could be found on type " + nextField.getDeclaringClass().getSimpleName()); } } } if (order < 0 && order != Child.ORDER_UNKNOWN) { throw new ConfigurationException("Invalid order '" + order + "' on @Child for field '" + nextField.getName() + "' on target type: " + declaringClass); } if (order != Child.ORDER_UNKNOWN && !orderIsReplaceParent) { order = order + baseElementOrder; } // int min = childAnnotation.min(); // int max = childAnnotation.max(); /* * Anything that's marked as unknown is given a new ID that is <0 so that it doesn't conflict with any given IDs and can be figured out later */ if (order == Child.ORDER_UNKNOWN) { order = Integer.valueOf(0); while (orderMap.containsKey(order)) { order++; } } List<Class<? extends IBase>> choiceTypes = next.getChoiceTypes(); if (orderMap.containsKey(order)) { throw new ConfigurationException("Detected duplicate field order '" + childAnnotation.order() + "' for element named '" + elementName + "' in type '" + declaringClass.getCanonicalName() + "' - Already had: " + orderMap.get(order).getElementName()); } if (elementNames.contains(elementName)) { throw new ConfigurationException("Detected duplicate field name '" + elementName + "' in type '" + declaringClass.getCanonicalName() + "'"); } Class<?> nextElementType = next.getElementType(); BaseRuntimeDeclaredChildDefinition def; if (childAnnotation.name().equals("extension") && IBaseExtension.class.isAssignableFrom(nextElementType)) { def = new RuntimeChildExtension(nextField, childAnnotation.name(), childAnnotation, descriptionAnnotation); } else if (childAnnotation.name().equals("modifierExtension") && IBaseExtension.class.isAssignableFrom(nextElementType)) { def = new RuntimeChildExtension(nextField, childAnnotation.name(), childAnnotation, descriptionAnnotation); } else if (BaseContainedDt.class.isAssignableFrom(nextElementType) || (childAnnotation.name().equals("contained") && IBaseResource.class.isAssignableFrom(nextElementType))) { /* * Child is contained resources */ def = new RuntimeChildContainedResources(nextField, childAnnotation, descriptionAnnotation, elementName); } else if (IAnyResource.class.isAssignableFrom(nextElementType) || IResource.class.equals(nextElementType)) { /* * Child is a resource as a direct child, as in Bundle.entry.resource */ def = new RuntimeChildDirectResource(nextField, childAnnotation, descriptionAnnotation, elementName); } else { childIsChoiceType |= choiceTypes.size() > 1; if (childIsChoiceType && !BaseResourceReferenceDt.class.isAssignableFrom(nextElementType) && !IBaseReference.class.isAssignableFrom(nextElementType)) { def = new RuntimeChildChoiceDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, choiceTypes); } else if (extensionAttr != null) { /* * Child is an extension */ Class<? extends IBase> et = (Class<? extends IBase>) nextElementType; Object binder = null; if (BoundCodeDt.class.isAssignableFrom(nextElementType) || IBoundCodeableConcept.class.isAssignableFrom(nextElementType)) { binder = ModelScanner.getBoundCodeBinder(nextField); } def = new RuntimeChildDeclaredExtensionDefinition(nextField, childAnnotation, descriptionAnnotation, extensionAttr, elementName, extensionAttr.url(), et, binder); if (IBaseEnumeration.class.isAssignableFrom(nextElementType)) { ((RuntimeChildDeclaredExtensionDefinition) def).setEnumerationType( ReflectionUtil.getGenericCollectionTypeOfFieldWithSecondOrderForList(nextField)); } } else if (BaseResourceReferenceDt.class.isAssignableFrom(nextElementType) || IBaseReference.class.isAssignableFrom(nextElementType)) { /* * Child is a resource reference */ List<Class<? extends IBaseResource>> refTypesList = new ArrayList<Class<? extends IBaseResource>>(); for (Class<? extends IElement> nextType : childAnnotation.type()) { if (IBaseReference.class.isAssignableFrom(nextType)) { refTypesList.add(myContext.getVersion().getVersion().isRi() ? IAnyResource.class : IResource.class); continue; } else if (IBaseResource.class.isAssignableFrom(nextType) == false) { throw new ConfigurationException("Field '" + nextField.getName() + "' in class '" + nextField.getDeclaringClass().getCanonicalName() + "' is of type " + BaseResourceReferenceDt.class + " but contains a non-resource type: " + nextType.getCanonicalName()); } refTypesList.add((Class<? extends IBaseResource>) nextType); } def = new RuntimeChildResourceDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, refTypesList); } else if (IResourceBlock.class.isAssignableFrom(nextElementType) || IBaseBackboneElement.class.isAssignableFrom(nextElementType) || IBaseDatatypeElement.class.isAssignableFrom(nextElementType)) { /* * Child is a resource block (i.e. a sub-tag within a resource) TODO: do these have a better name according to HL7? */ Class<? extends IBase> blockDef = (Class<? extends IBase>) nextElementType; def = new RuntimeChildResourceBlockDefinition(myContext, nextField, childAnnotation, descriptionAnnotation, elementName, blockDef); } else if (IDatatype.class.equals(nextElementType) || IElement.class.equals(nextElementType) || "Type".equals(nextElementType.getSimpleName()) || IBaseDatatype.class.equals(nextElementType)) { def = new RuntimeChildAny(nextField, elementName, childAnnotation, descriptionAnnotation); } else if (IDatatype.class.isAssignableFrom(nextElementType) || IPrimitiveType.class.isAssignableFrom(nextElementType) || ICompositeType.class.isAssignableFrom(nextElementType) || IBaseDatatype.class.isAssignableFrom(nextElementType) || IBaseExtension.class.isAssignableFrom(nextElementType)) { Class<? extends IBase> nextDatatype = (Class<? extends IBase>) nextElementType; if (IPrimitiveType.class.isAssignableFrom(nextElementType)) { if (nextElementType.equals(BoundCodeDt.class)) { IValueSetEnumBinder<Enum<?>> binder = ModelScanner.getBoundCodeBinder(nextField); Class<? extends Enum<?>> enumType = ModelScanner .determineEnumTypeForBoundField(nextField); def = new RuntimeChildPrimitiveBoundCodeDatatypeDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, nextDatatype, binder, enumType); } else if (IBaseEnumeration.class.isAssignableFrom(nextElementType)) { Class<? extends Enum<?>> binderType = ModelScanner .determineEnumTypeForBoundField(nextField); def = new RuntimeChildPrimitiveEnumerationDatatypeDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, nextDatatype, binderType); } else { def = new RuntimeChildPrimitiveDatatypeDefinition(nextField, elementName, descriptionAnnotation, childAnnotation, nextDatatype); } } else { if (IBoundCodeableConcept.class.isAssignableFrom(nextElementType)) { IValueSetEnumBinder<Enum<?>> binder = ModelScanner.getBoundCodeBinder(nextField); Class<? extends Enum<?>> enumType = ModelScanner .determineEnumTypeForBoundField(nextField); def = new RuntimeChildCompositeBoundDatatypeDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, nextDatatype, binder, enumType); } else if (BaseNarrativeDt.class.isAssignableFrom(nextElementType) || INarrative.class.isAssignableFrom(nextElementType)) { def = new RuntimeChildNarrativeDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, nextDatatype); } else { def = new RuntimeChildCompositeDatatypeDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, nextDatatype); } } } else { throw new ConfigurationException( "Field '" + elementName + "' in type '" + declaringClass.getCanonicalName() + "' is not a valid child type: " + nextElementType); } Binding bindingAnnotation = ModelScanner.pullAnnotation(nextField, Binding.class); if (bindingAnnotation != null) { if (isNotBlank(bindingAnnotation.valueSet())) { def.setBindingValueSet(bindingAnnotation.valueSet()); } } } orderMap.put(order, def); elementNames.add(elementName); } }
From source file:org.apache.rocketmq.tools.command.consumer.ConsumerSubCommand.java
@Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try {/*from w w w . j a v a 2 s. c om*/ defaultMQAdminExt.start(); String group = commandLine.getOptionValue('g').trim(); ConsumerConnection cc = defaultMQAdminExt.examineConsumerConnectionInfo(group); boolean jstack = commandLine.hasOption('s'); if (!commandLine.hasOption('i')) { int i = 1; long now = System.currentTimeMillis(); final TreeMap<String/* clientId */, ConsumerRunningInfo> criTable = new TreeMap<String, ConsumerRunningInfo>(); for (Connection conn : cc.getConnectionSet()) { try { ConsumerRunningInfo consumerRunningInfo = defaultMQAdminExt.getConsumerRunningInfo(group, conn.getClientId(), jstack); if (consumerRunningInfo != null) { criTable.put(conn.getClientId(), consumerRunningInfo); String filePath = now + "/" + conn.getClientId(); MixAll.string2FileNotSafe(consumerRunningInfo.formatString(), filePath); System.out.printf("%03d %-40s %-20s %s%n", i++, conn.getClientId(), MQVersion.getVersionDesc(conn.getVersion()), filePath); } } catch (Exception e) { e.printStackTrace(); } } if (!criTable.isEmpty()) { boolean subSame = ConsumerRunningInfo.analyzeSubscription(criTable); boolean rebalanceOK = subSame && ConsumerRunningInfo.analyzeRebalance(criTable); if (subSame) { System.out.printf("%n%nSame subscription in the same group of consumer"); System.out.printf("%n%nRebalance %s%n", rebalanceOK ? "OK" : "Failed"); Iterator<Entry<String, ConsumerRunningInfo>> it = criTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, ConsumerRunningInfo> next = it.next(); String result = ConsumerRunningInfo.analyzeProcessQueue(next.getKey(), next.getValue()); if (result.length() > 0) { System.out.printf("%s", result); } } } else { System.out.printf("%n%nWARN: Different subscription in the same group of consumer!!!"); } } } else { String clientId = commandLine.getOptionValue('i').trim(); ConsumerRunningInfo consumerRunningInfo = defaultMQAdminExt.getConsumerRunningInfo(group, clientId, jstack); if (consumerRunningInfo != null) { System.out.printf("%s", consumerRunningInfo.formatString()); } } } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } }
From source file:org.apache.rocketmq.tools.command.consumer.ConsumerStatusSubCommand.java
@Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try {/*from w w w . j a va 2 s. c o m*/ defaultMQAdminExt.start(); String group = commandLine.getOptionValue('g').trim(); ConsumerConnection cc = defaultMQAdminExt.examineConsumerConnectionInfo(group); boolean jstack = commandLine.hasOption('s'); if (!commandLine.hasOption('i')) { int i = 1; long now = System.currentTimeMillis(); final TreeMap<String/* clientId */, ConsumerRunningInfo> criTable = new TreeMap<String, ConsumerRunningInfo>(); for (Connection conn : cc.getConnectionSet()) { try { ConsumerRunningInfo consumerRunningInfo = defaultMQAdminExt.getConsumerRunningInfo(group, conn.getClientId(), jstack); if (consumerRunningInfo != null) { criTable.put(conn.getClientId(), consumerRunningInfo); String filePath = now + "/" + conn.getClientId(); MixAll.string2FileNotSafe(consumerRunningInfo.formatString(), filePath); System.out.printf("%03d %-40s %-20s %s%n", i++, conn.getClientId(), MQVersion.getVersionDesc(conn.getVersion()), filePath); } } catch (Exception e) { e.printStackTrace(); } } if (!criTable.isEmpty()) { boolean subSame = ConsumerRunningInfo.analyzeSubscription(criTable); boolean rebalanceOK = subSame && ConsumerRunningInfo.analyzeRebalance(criTable); if (subSame) { System.out.printf("%n%nSame subscription in the same group of consumer"); System.out.printf("%n%nRebalance %s%n", rebalanceOK ? "OK" : "Failed"); Iterator<Entry<String, ConsumerRunningInfo>> it = criTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, ConsumerRunningInfo> next = it.next(); String result = ConsumerRunningInfo.analyzeProcessQueue(next.getKey(), next.getValue()); if (result.length() > 0) { System.out.printf("%s", result); } } } else { System.out.printf("%n%nWARN: Different subscription in the same group of consumer!!!"); } } } else { String clientId = commandLine.getOptionValue('i').trim(); ConsumerRunningInfo consumerRunningInfo = defaultMQAdminExt.getConsumerRunningInfo(group, clientId, jstack); if (consumerRunningInfo != null) { System.out.printf("%s", consumerRunningInfo.formatString()); } } } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } }
From source file:com.askjeffreyliu.camera2barcode.camera.CameraSource.java
private Size getBestAspectPictureSize(android.util.Size[] supportedPictureSizes) { float targetRatio = Utils.getScreenRatio(mContext); Size bestSize = null;/*from ww w. java 2 s .co m*/ TreeMap<Double, List> diffs = new TreeMap<>(); for (android.util.Size size : supportedPictureSizes) { float ratio = (float) size.getWidth() / size.getHeight(); double diff = Math.abs(ratio - targetRatio); if (diff < maxRatioTolerance) { if (diffs.keySet().contains(diff)) { //add the value to the list diffs.get(diff).add(size); } else { List newList = new ArrayList<>(); newList.add(size); diffs.put(diff, newList); } } } //diffs now contains all of the usable sizes //now let's see which one has the least amount of for (Map.Entry entry : diffs.entrySet()) { List<android.util.Size> entries = (List) entry.getValue(); for (android.util.Size s : entries) { if (bestSize == null) { bestSize = new Size(s.getWidth(), s.getHeight()); } else if (bestSize.getWidth() < s.getWidth() || bestSize.getHeight() < s.getHeight()) { bestSize = new Size(s.getWidth(), s.getHeight()); } } } return bestSize; }
From source file:com.hichinaschool.flashcards.async.DeckTask.java
private TaskData doInBackgroundConfSetSubdecks(TaskData... params) { // Log.i(AnkiDroidApp.TAG, "doInBackgroundConfSetSubdecks"); Object[] data = params[0].getObjArray(); Collection col = (Collection) data[0]; JSONObject deck = (JSONObject) data[1]; JSONObject conf = (JSONObject) data[2]; try {/* w w w.j a v a 2s. com*/ TreeMap<String, Long> children = col.getDecks().children(deck.getLong("id")); for (Map.Entry<String, Long> entry : children.entrySet()) { JSONObject child = col.getDecks().get(entry.getValue()); if (child.getInt("dyn") == 1) { continue; } TaskData newParams = new TaskData(new Object[] { col, child, conf }); boolean changed = doInBackgroundConfChange(newParams).getBoolean(); if (!changed) { return new TaskData(false); } } return new TaskData(true); } catch (JSONException e) { return new TaskData(false); } }
From source file:com.gp.cong.logisoft.bc.fcl.SedFilingBC.java
public void readAesResponse() throws Exception { String aesFilesFolder = ""; String dateFolder = DateUtils.formatDate(new Date(), "yyyy/MM/dd") + "/"; String osName = System.getProperty("os.name").toLowerCase(); if (osName.contains("linux")) { aesFilesFolder = LoadEdiProperties.getProperty("linuxAesResponseFile"); } else {/* w ww . ja va 2 s . com*/ aesFilesFolder = LoadEdiProperties.getProperty("aesResopnseFile"); } if (null != aesFilesFolder) { File folder = new File(aesFilesFolder); if (!folder.exists()) { folder.mkdirs(); } File processedFolder = new File(aesFilesFolder + "processed/" + dateFolder); if (!processedFolder.exists()) { processedFolder.mkdirs(); } File unprocessedFolder = new File(aesFilesFolder + "unprocessed/" + dateFolder); if (!unprocessedFolder.exists()) { unprocessedFolder.mkdirs(); } File[] filesInFolder = folder.listFiles(); TreeMap<String, String> fileMap = new TreeMap<String, String>(); for (File filesInFolder1 : filesInFolder) { if (filesInFolder1.isFile()) { String aesResponseFileName = filesInFolder1.getName(); String key = ""; if (aesResponseFileName.contains(".aes")) { key = aesResponseFileName.substring(0, aesResponseFileName.lastIndexOf(".aes")); fileMap.put(key, aesResponseFileName); } else if (aesResponseFileName.contains(".resp")) { key = aesResponseFileName.substring(0, aesResponseFileName.lastIndexOf(".resp")); fileMap.put(key, aesResponseFileName); } } } for (Map.Entry<String, String> entry : fileMap.entrySet()) { String fileName = entry.getValue(); if (fileName.contains(".aes")) { InputStream aesinInputStream = new FileInputStream(aesFilesFolder + fileName); try { readAesResponseFile(aesinInputStream, aesFilesFolder, fileName); aesinInputStream.close(); File deleteFile = new File(aesFilesFolder + fileName); if (deleteFile.exists()) { deleteFile.renameTo( new File(aesFilesFolder + "processed/" + dateFolder + deleteFile.getName())); deleteFile.deleteOnExit(); } } catch (JDBCConnectionException e) { throw e; } catch (Exception e) { aesinInputStream.close(); File deleteFile = new File(aesFilesFolder + fileName); if (deleteFile.exists()) { deleteFile.renameTo( new File(aesFilesFolder + "unprocessed/" + dateFolder + deleteFile.getName())); deleteFile.deleteOnExit(); } } } else if (fileName.contains(".resp")) { InputStream respInputStream = new FileInputStream(aesFilesFolder + fileName); try { readRespResponseFile(respInputStream, aesFilesFolder, fileName); respInputStream.close(); File deleteFile = new File(aesFilesFolder + fileName); if (deleteFile.exists()) { deleteFile.renameTo( new File(aesFilesFolder + "processed/" + dateFolder + deleteFile.getName())); deleteFile.deleteOnExit(); } } catch (JDBCConnectionException e) { throw e; } catch (Exception e) { respInputStream.close(); File deleteFile = new File(aesFilesFolder + fileName); if (deleteFile.exists()) { deleteFile.renameTo( new File(aesFilesFolder + "unprocessed/" + dateFolder + deleteFile.getName())); deleteFile.deleteOnExit(); } } } } } }
From source file:org.opendatakit.common.persistence.engine.gae.TaskLockImpl.java
/** * Update the MemCache for (formId, taskType) to record the given timestamp as * the expire-time of the lockId. The lockId with the earliest in-the-future * expire-time wins as long as there are no other lockIds within * SHORTEST_ALLOWABLE_GAIN_LOCK_SEPARATION of it. * //from w w w . j a va2 s.co m * @param lockId * @param formId * @param taskType * @param timestamp * @throws ODKTaskLockException */ private synchronized void updateLockIdTimestampMemCache(String lockId, String formId, ITaskLockType taskType, Long timestamp) throws ODKTaskLockException { if (syncCache != null) { int i; try { String formTask = ((formId == null) ? "" : formId) + "@" + taskType.getName(); for (i = 0; i < 10; i++) { IdentifiableValue v = syncCache.contains(formTask) ? syncCache.getIdentifiable(formTask) : null; if (v == null || v.getValue() == null) { TreeMap<Long, String> tm = new TreeMap<Long, String>(); tm.put(timestamp, lockId); if (syncCache.put(formTask, tm, null, SetPolicy.ADD_ONLY_IF_NOT_PRESENT)) { break; } } else { @SuppressWarnings("unchecked") TreeMap<Long, String> tmOrig = (TreeMap<Long, String>) v.getValue(); TreeMap<Long, String> tm = new TreeMap<Long, String>(tmOrig); // remove any old entries for lockId and any that are very old Long currentTimestamp = System.currentTimeMillis(); Long oldTimestamp; do { oldTimestamp = null; for (Map.Entry<Long, String> entry : tm.entrySet()) { if (entry.getKey() + 300000L < currentTimestamp) { // more than 5 minutes old -- remove it oldTimestamp = entry.getKey(); break; } if (entry.getValue().equals(lockId)) { oldTimestamp = entry.getKey(); break; } } if (oldTimestamp != null) { tm.remove(oldTimestamp); } } while (oldTimestamp != null); // update with new timestamp if (tm.put(timestamp, lockId) != null) { // some other thread gained the lock first for this timestamp throw new ODKTaskLockException(MULTIPLE_MEMCACHE_RESULTS_ERROR); } // try to update the Memcache with these changes. if (syncCache.putIfUntouched(formTask, v, tm)) { break; } } } } catch (ODKTaskLockException e) { throw e; } catch (Throwable t) { t.printStackTrace(); throw new ODKTaskLockException(OTHER_ERROR, t); } if (i == 10) { // crazy contention throw new ODKTaskLockException(HOT_MEMCACHE_ENTRY_ERROR); } } }
From source file:org.eurocarbdb.application.glycoworkbench.plugin.PeakListChartPanel.java
public void addIsotopeCurves(TreeMap<Peak, Collection<Annotation>> annotations) { if (theDocument.size() == 0) return;//from ww w . j a va2s . c om // remove old curves removeIsotopeCurves(); // add curves if (annotations != null) { // set renderer if (show_all_isotopes) { thePlot.setRenderer(1, new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES)); thePlot.getRenderer(1).setShape(new Ellipse2D.Double(0, 0, 7, 7)); } else thePlot.setRenderer(1, new StandardXYItemRenderer(StandardXYItemRenderer.LINES)); MSUtils.IsotopeList isotope_list = new MSUtils.IsotopeList(show_all_isotopes); for (Map.Entry<Peak, Collection<Annotation>> pa : annotations.entrySet()) { Peak p = pa.getKey(); // get compositions HashSet<Molecule> compositions = new HashSet<Molecule>(); for (Annotation a : pa.getValue()) { try { compositions.add(a.getFragmentEntry().fragment.computeIon()); } catch (Exception e) { e.printStackTrace(); } } // collect curves for this peak HashMap<String, double[][]> all_curves = new HashMap<String, double[][]>(); for (Molecule m : compositions) { try { double[][] data = MSUtils.getIsotopesCurve(1, m, show_all_isotopes); // overlay the distribution with the existing list of isotopes isotope_list.adjust(data, p.getMZ(), p.getIntensity()); all_curves.put(m.toString(), data); } catch (Exception e) { LogUtils.report(e); } } // add average curve for this peak if (all_curves.size() > 1) { double[][] data = MSUtils.average(all_curves.values(), show_all_isotopes); // add the average to the chart String name = "average-" + p.getMZ(); theIsotopesDataset.addSeries(name, data); thePlot.getRenderer(1).setSeriesPaint(theIsotopesDataset.indexOf(name), Color.magenta); thePlot.getRenderer(1).setSeriesStroke(theIsotopesDataset.indexOf(name), new BasicStroke(2)); // add the average to the isotope list isotope_list.add(data, false); } else if (all_curves.size() == 1) { // add the only curve to the isotope list isotope_list.add(all_curves.values().iterator().next(), false); } // add the other curves for (Map.Entry<String, double[][]> e : all_curves.entrySet()) { String name = e.getKey() + "-" + p.getMZ(); theIsotopesDataset.addSeries(name, e.getValue()); thePlot.getRenderer(1).setSeriesPaint(theIsotopesDataset.indexOf(name), Color.blue); } } } updateIntensityAxis(); }
From source file:org.carewebframework.ui.xml.ZK2XML.java
/** * Adds the root component to the XML document at the current level along with all bean * properties that return String or primitive types. Then, recurses over all of the root * component's children./*from w ww. j av a 2 s . c o m*/ * * @param root The root component. * @param parent The parent XML node. */ private void toXML(Component root, Node parent) { TreeMap<String, String> properties = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); Class<?> clazz = root.getClass(); ComponentDefinition def = root.getDefinition(); String cmpname = def.getName(); if (def.getImplementationClass() != clazz) { properties.put("use", clazz.getName()); } if (def.getApply() != null) { properties.put("apply", def.getApply()); } Node child = doc.createElement(cmpname); parent.appendChild(child); for (PropertyDescriptor propDx : PropertyUtils.getPropertyDescriptors(root)) { Method getter = propDx.getReadMethod(); Method setter = propDx.getWriteMethod(); String name = propDx.getName(); if (getter != null && setter != null && !isExcluded(name, cmpname, null) && !setter.isAnnotationPresent(Deprecated.class) && (getter.getReturnType() == String.class || getter.getReturnType().isPrimitive())) { try { Object raw = getter.invoke(root); String value = raw == null ? null : raw.toString(); if (StringUtils.isEmpty(value) || ("id".equals(name) && value.startsWith("z_")) || isExcluded(name, cmpname, value)) { continue; } properties.put(name, value.toString()); } catch (Exception e) { } } } for (Entry<String, String> entry : properties.entrySet()) { Attr attr = doc.createAttribute(entry.getKey()); child.getAttributes().setNamedItem(attr); attr.setValue(entry.getValue()); } properties = null; for (Component cmp : root.getChildren()) { toXML(cmp, child); } }
From source file:net.tsquery.LastEndpoint.java
@SuppressWarnings("unchecked") private JSONObject PlotToStandardJSON(Plot plot, long tsFrom, long tsTo, int topN) { final JSONObject plotObject = new JSONObject(); JSONArray seriesArray = new JSONArray(); final TreeMap<Double, JSONObject> weightMap = new TreeMap<>(Collections.reverseOrder()); for (DataPoints dataPoints : plot.getDataPoints()) { double weight = 0; JSONArray dataArray = new JSONArray(); StringBuilder nameBuilder = new StringBuilder(); nameBuilder.append(dataPoints.metricName()).append(": "); Map<String, String> tags = dataPoints.getTags(); for (String s : tags.keySet()) { nameBuilder.append(String.format("%s=%s, ", s, tags.get(s))); }/*ww w. j ava 2s . c o m*/ nameBuilder.setLength(nameBuilder.length() - 2); JSONArray values = null; long latestTimestamp = 0; for (DataPoint point : dataPoints) { long timestamp = point.timestamp(); if (!(timestamp < tsFrom || timestamp > tsTo) && timestamp > latestTimestamp) { latestTimestamp = timestamp; double dpValue = getValue(point); values = new JSONArray(); values.add(timestamp * 1000); values.add(dpValue); } } dataArray.add(values); JSONObject series = new JSONObject(); series.put("name", nameBuilder.toString()); series.put("data", dataArray); while (weightMap.containsKey(weight)) weight -= 0.00000001; weightMap.put(weight, series); } int counter = 0; for (Map.Entry<Double, JSONObject> entry : weightMap.entrySet()) { seriesArray.add(entry.getValue()); ++counter; if ((topN > 0) && (counter >= topN)) break; } plotObject.put("plot", seriesArray); return plotObject; }