List of usage examples for java.util TreeMap get
public V get(Object key)
From source file:com.npower.dm.model.TestGenerateModelXMLByWurfl.java
public void testOutputXML() throws Exception { WurflSource source = new FileWurflSource( new File("D:\\zhao\\MyWorkspace\\nWave-DM-Common\\metadata\\wurfl\\wurfl.xml")); ObjectsManager om = ObjectsManager.newInstance(source); ListManager lm = om.getListManagerInstance(); TreeMap<String, WurflDevice> load = lm.getActualDeviceElementsList(); Set<String> sortedBrands = new TreeSet<String>(); sortedBrands.addAll(load.keySet());// w w w .ja v a 2 s. c om Map<String, Set<String>> maps = new TreeMap<String, Set<String>>(); Map<String, String> brandNames = new TreeMap<String, String>(); for (String brand : sortedBrands) { // System.out.print("'"+key+"',"); WurflDevice wd = (WurflDevice) load.get(brand); System.out.print("'" + brand + "',"); System.out.print("'" + wd.getBrandName() + "',"); System.out.println("'" + wd.getModelName() + "'"); if (maps.get(wd.getBrandName().toLowerCase()) == null) { maps.put(wd.getBrandName().toLowerCase(), new TreeSet<String>()); } maps.get(wd.getBrandName().toLowerCase()).add(wd.getModelName()); if (brandNames.get(wd.getBrandName().toLowerCase()) == null) { brandNames.put(wd.getBrandName().toLowerCase(), wd.getBrandName()); } } System.out.println(maps); //String outputBaseDir = "D:/Zhao/MyWorkspace/nWave-DM-Common/metadata/setup"; String outputBaseDir = "C:/temp/setup"; outputManufacturersXML(maps, brandNames, outputBaseDir); outputModelsXML(maps, brandNames, outputBaseDir); File setupFile = new File(outputBaseDir, "dmsetup.2nd.xml"); BufferedWriter out = new BufferedWriter(new FileWriter(setupFile)); out.write("<Setup>\n"); out.write(" <Name>OTAS DM Setup</Name>\n"); out.write(" <Description>OTAS DM Setup</Description>\n"); out.write(" <Properties>\n"); out.write(" <!-- Please customize the following properties -->\n"); out.write(" <Property key=\"jdbc.driver.class\"\n"); out.write(" value=\"oracle.jdbc.driver.OracleDriver\" />\n"); out.write(" <Property key=\"jdbc.url\"\n"); out.write(" value=\"jdbc:oracle:thin:@192.168.0.4:1521:orcl\" />\n"); out.write(" <Property key=\"jdbc.autoCommit\"\n"); out.write(" value=\"false\" />\n"); out.write(" <Property key=\"jdbc.super.user\"\n"); out.write(" value=\"system\" />\n"); out.write(" <Property key=\"jdbc.super.password\"\n"); out.write(" value=\"admin123\" />\n"); out.write(" <Property key=\"jdbc.dmuser.user\"\n"); out.write(" value=\"otasdm\" />\n"); out.write(" <Property key=\"jdbc.dmuser.password\"\n"); out.write(" value=\"otasdm\" />\n"); out.write(" \n"); out.write(" <!-- Do not modified the following properties -->\n"); out.write(" <!-- Database connection parameters -->\n"); out.write(" <Property key=\"hibernate.dialect\" value=\"org.hibernate.dialect.Oracle9Dialect\"/>\n"); out.write(" <Property key=\"hibernate.connection.driver_class\" value=\"${jdbc.driver.class}\"/>\n"); out.write(" <Property key=\"hibernate.connection.url\" value=\"${jdbc.url}\"/>\n"); out.write(" <Property key=\"hibernate.connection.username\" value=\"${jdbc.dmuser.user}\"/>\n"); out.write(" <Property key=\"hibernate.connection.password\" value=\"${jdbc.dmuser.password}\"/>\n"); out.write(" \n"); out.write(" <!-- Model library parameters -->\n"); out.write(" <Property key=\"model.default.icon.file\" value=\"./models/default_model.jpg\"/>\n"); out.write(" \n"); out.write(" </Properties>\n"); out.write(" \n"); out.write(" <Console class=\"com.npower.setup.console.ConsoleImpl\"></Console>\n"); out.write(" \n"); out.write(" <Tasks>\n"); out.write(" <!-- Step#9: Import Manufacturers and Models -->\n"); out.write(" <Task disable=\"false\">\n"); out.write(" <Name>Setup DM Manufacturers and Models (2nd stage)</Name>\n"); out.write(" <Description>Setup DM Manufacturers and Models (2nd stage)</Description>\n"); out.write("\n"); out.write(" <!-- Import Manufacturers -->\n"); out.write(" <Task class=\"com.npower.dm.setup.task.ManufacturerTask\">\n"); out.write(" <Name>Import Manufacturers</Name>\n"); out.write(" <Description>Import Manufacturers</Description>\n"); out.write(" <Properties>\n"); String files = ""; for (int i = 0; i < this.manufacturerFiles.size(); i++) { if (i < this.manufacturerFiles.size() - 1) { files += "./manufacturers/" + this.manufacturerFiles.get(i) + ",\n"; } else { files += "./manufacturers/" + this.manufacturerFiles.get(i) + "\n"; } } out.write(" <Property key=\"import.files\" value=\"" + files + "\" />\n"); out.write(" </Properties>\n"); out.write(" </Task>\n"); out.write(" \n"); for (int i = 0; i < this.modelFiles.size(); i++) { out.write(" <!-- Import " + this.modelNames.get(i) + " Models -->\n"); out.write(" <Task class=\"com.npower.dm.setup.task.ModelTask\">\n"); out.write(" <Name>Import " + this.modelNames.get(i) + " Models</Name>\n"); out.write(" <Description>Import " + this.modelNames.get(i) + " Models</Description>\n"); out.write(" <Properties>\n"); out.write(" <Property key=\"import.files\" value=\"" + this.modelFiles.get(i) + "\" />\n"); out.write(" </Properties>\n"); out.write(" </Task>\n"); out.write("\n"); } out.write(" </Task>\n"); out.write(" </Tasks>\n"); out.write("</Setup>\n"); out.close(); }
From source file:cn.teamlab.wg.framework.util.csv.CsvWriter.java
/** * Bean?CSV?// w w w . jav a 2s .c om * Bean@CsvPropAnno(index = ?) * @param objList * @return * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ public static String bean2Csv(List<?> objList) throws Exception { if (objList == null || objList.size() == 0) { return ""; } TreeMap<Integer, CsvFieldBean> map = new TreeMap<Integer, CsvFieldBean>(); Object bean0 = objList.get(0); Class<?> clazz = bean0.getClass(); PropertyDescriptor[] arr = org.springframework.beans.BeanUtils.getPropertyDescriptors(clazz); for (PropertyDescriptor p : arr) { String fieldName = p.getName(); Field field = FieldUtils.getDeclaredField(clazz, fieldName, true); if (field == null) { continue; } boolean isAnno = field.isAnnotationPresent(CsvFieldAnno.class); if (isAnno) { CsvFieldAnno anno = field.getAnnotation(CsvFieldAnno.class); int idx = anno.index(); map.put(idx, new CsvFieldBean(idx, anno.title(), fieldName)); } } // CSVBuffer StringBuffer buff = new StringBuffer(); // ??? boolean withTitle = clazz.isAnnotationPresent(CsvTitleAnno.class); // ??csv if (withTitle) { StringBuffer titleBuff = new StringBuffer(); for (int key : map.keySet()) { CsvFieldBean fieldBean = map.get(key); titleBuff.append(Letters.QUOTE).append(fieldBean.getTitle()).append(Letters.QUOTE); titleBuff.append(Letters.COMMA); } buff.append(StringUtils.chop(titleBuff.toString())); buff.append(Letters.LF); titleBuff.setLength(0); } for (Object o : objList) { StringBuffer tmpBuff = new StringBuffer(); for (int key : map.keySet()) { CsvFieldBean fieldBean = map.get(key); Object val = BeanUtils.getProperty(o, fieldBean.getFieldName()); if (val != null) { tmpBuff.append(Letters.QUOTE).append(val).append(Letters.QUOTE); } else { tmpBuff.append(StringUtils.EMPTY); } tmpBuff.append(Letters.COMMA); } buff.append(StringUtils.chop(tmpBuff.toString())); buff.append(Letters.LF); tmpBuff.setLength(0); } return buff.toString(); }
From source file:disAMS.AMRMClient.Impl.AMRMClientImpl.java
@Override public synchronized List<? extends Collection<T>> getMatchingRequests(Priority priority, String resourceName, Resource capability) {/* w ww .j a v a2 s . c o m*/ Preconditions.checkArgument(capability != null, "The Resource to be requested should not be null "); Preconditions.checkArgument(priority != null, "The priority at which to request containers should not be null "); List<LinkedHashSet<T>> list = new LinkedList<LinkedHashSet<T>>(); Map<String, TreeMap<Resource, ResourceRequestInfo>> remoteRequests = this.remoteRequestsTable.get(priority); if (remoteRequests == null) { return list; } TreeMap<Resource, ResourceRequestInfo> reqMap = remoteRequests.get(resourceName); if (reqMap == null) { return list; } ResourceRequestInfo resourceRequestInfo = reqMap.get(capability); if (resourceRequestInfo != null && !resourceRequestInfo.containerRequests.isEmpty()) { list.add(resourceRequestInfo.containerRequests); return list; } // no exact match. Container may be larger than what was requested. // get all resources <= capability. map is reverse sorted. SortedMap<Resource, ResourceRequestInfo> tailMap = reqMap.tailMap(capability); for (Map.Entry<Resource, ResourceRequestInfo> entry : tailMap.entrySet()) { if (canFit(entry.getKey(), capability) && !entry.getValue().containerRequests.isEmpty()) { // match found that fits in the larger resource list.add(entry.getValue().containerRequests); } } // no match found return list; }
From source file:model.plate.ANATestResult.java
public void diagnose2(double control) { //titer,positivity,r2,pattern final Comparator<DiagnosisConstant.ANA_Titer> titerComparator = new Comparator<DiagnosisConstant.ANA_Titer>() { @Override//from w ww . j a v a2 s . c o m public int compare(DiagnosisConstant.ANA_Titer t, DiagnosisConstant.ANA_Titer t1) { if (t.getId() < 0) { throw new RuntimeException("Titer: " + t.name()); } if (t1.getId() < 0) { throw new RuntimeException("Titer: " + t.name()); } if (t.getId() > 6) { throw new RuntimeException("Titer: " + t.name()); } if (t1.getId() > 6) { throw new RuntimeException("Titer: " + t.name()); } return t.getId() < t1.getId() ? -1 : t.getId() == t1.getId() ? 0 : 1; } }; TreeMap<DiagnosisConstant.ANA_Titer, Double> decreasingSignals = new TreeMap<>(titerComparator); decreasingSignals.putAll(signals); SimpleRegression regression = new SimpleRegression(); Iterator<DiagnosisConstant.ANA_Titer> it = decreasingSignals.keySet().iterator(); DiagnosisConstant.ANA_Titer t; Double signal; while (it.hasNext()) { t = it.next(); signal = decreasingSignals.get(t); if (signal == null) continue; // posCtrl=signal>posCtrl?signal:posCtrl; ??1:40, regression.addData((double) t.getId(), signal); if (signal > control) {// * PlateConstants.PositiveCutOffRatio titer = t; } } r2 = regression.getRSquare(); if (r2 < PlateConstants.R2_TH) { warningMessage.add(WarningMessage.SampleLinearity.getId()); } if (titer == null) titer = DiagnosisConstant.ANA_Titer.ANA_LESS_1_40; if (DiagnosisConstant.ANA_Titer.ANA_LESS_1_40.equals(titer) || titer.getId() < 2) {//1:40 System.out.println(); for (DiagnosisConstant.ANA_Titer t1 : decreasingSignals.keySet()) { System.out.println( this.julien_barcode + " Sample vs Control (th=" + PlateConstants.PositiveCutOffRatio + ")"); System.out.println(t1 + ": signal=" + decreasingSignals.get(t1) + "\tv.s.\tcontrol=" + control + " (" + decreasingSignals.get(t1) / control + ")"); } System.out.println(); positivity = DiagnosisConstant.ANA_Result.NEGATIVE; warningMessage.add(WarningMessage.WeakPositive.getId()); } else { positivity = DiagnosisConstant.ANA_Result.POSITIVE; } }
From source file:com.sfs.whichdoctor.dao.BulkContactDAOImpl.java
/** * Prepare the bulk contact bean.//from w w w. ja v a2 s . c o m * * @param contactBean the bulk contact bean * @param exportMap the export map * @param user the user * @return the bulk contact bean */ public final BulkContactBean prepare(final BulkContactBean contactBean, final TreeMap<String, ItemBean> exportMap, final UserBean user) { TreeMap<Integer, Integer> exportGUIDs = new TreeMap<Integer, Integer>(); Collection<Object> guids = new ArrayList<Object>(); /** Get a list of the unique GUIDs **/ for (String key : exportMap.keySet()) { try { ItemBean details = (ItemBean) exportMap.get(key); exportGUIDs.put(details.getObject1GUID(), details.getObject1GUID()); } catch (Exception e) { dataLogger.error("Error casting object to export map: " + e.getMessage()); } } for (Integer guid : exportGUIDs.keySet()) { guids.add(guid); } BulkContactBean bulkContact = performSearch(contactBean, guids, user, true); return bulkContact; }
From source file:net.spfbl.core.Reverse.java
public static ArrayList<String> getMXSet(String host) throws NamingException { TreeMap<Integer, TreeSet<String>> mxMap = new TreeMap<Integer, TreeSet<String>>(); Attributes atributes = Server.getAttributesDNS(host, new String[] { "MX" }); if (atributes == null || atributes.size() == 0) { atributes = Server.getAttributesDNS(host, new String[] { "CNAME" }); Attribute attribute = atributes.get("CNAME"); if (attribute != null) { String cname = (String) attribute.get(0); return getMXSet(cname); }// w ww.j a va2s . c o m } else { Attribute attribute = atributes.get("MX"); if (attribute != null) { for (int index = 0; index < attribute.size(); index++) { try { String mx = (String) attribute.get(index); int space = mx.indexOf(' '); String value = mx.substring(0, space); int priority = Integer.parseInt(value); mx = mx.substring(space + 1); int last = mx.length() - 1; TreeSet<String> mxSet = mxMap.get(priority); if (mxSet == null) { mxSet = new TreeSet<String>(); mxMap.put(priority, mxSet); } if (Subnet.isValidIP(mx.substring(0, last))) { mxSet.add(Subnet.normalizeIP(mx.substring(0, last))); } else if (Domain.isHostname(mx)) { mxSet.add(Domain.normalizeHostname(mx, true)); } } catch (NumberFormatException ex) { } } } } ArrayList<String> mxList = new ArrayList<String>(); if (mxMap.isEmpty()) { // https://tools.ietf.org/html/rfc5321#section-5 mxList.add(Domain.normalizeHostname(host, true)); } else { for (int priority : mxMap.keySet()) { TreeSet<String> mxSet = mxMap.get(priority); for (String mx : mxSet) { if (!mxList.contains(mx)) { mxList.add(mx); } } } } return mxList; }
From source file:com.act.biointerpretation.mechanisminspection.MechanisticValidator.java
private TreeMap<Integer, List<Ero>> findBestRosThatCorrectlyComputeTheReaction(Reaction rxn, Long newRxnId) throws IOException { /* Look up any cached results and return immediately if they're available. * Note: this only works while EROs ignore cofactors. If cofactors need to be involved, we should just remove this. *//*ww w. j a v a2s .c o m*/ Map<Long, Integer> substrateToCoefficientMap = new HashMap<>(); Map<Long, Integer> productToCoefficientMap = new HashMap<>(); for (Long id : rxn.getSubstrates()) { substrateToCoefficientMap.put(id, rxn.getSubstrateCoefficient(id)); } for (Long id : rxn.getProducts()) { productToCoefficientMap.put(id, rxn.getSubstrateCoefficient(id)); } { Pair<Long, TreeMap<Integer, List<Ero>>> cachedResults = cachedEroResults .get(Pair.of(substrateToCoefficientMap, productToCoefficientMap)); if (cachedResults != null) { LOGGER.debug("Got hit on cached ERO results: %d == %d", newRxnId, cachedResults.getLeft()); cacheHitCounter++; return cachedResults.getRight(); } } List<Molecule> substrateMolecules = new ArrayList<>(); for (Long id : rxn.getSubstrates()) { String inchi = mapNewChemIdToInChI(id); if (inchi == null) { String msg = String.format("Missing inchi for new chem id %d in cache", id); LOGGER.error(msg); throw new RuntimeException(msg); } if (inchi.contains("FAKE")) { LOGGER.debug("The inchi is a FAKE, so just ignore the chemical."); continue; } Molecule mol; try { mol = MolImporter.importMol(blacklistedInchisCorpus.renameInchiIfFoundInBlacklist(inchi)); // We had to clean the molecule after importing since based on our testing, the RO only matched the molecule // once we cleaned it. Else, the RO did not match the chemical. Cleaner.clean(mol, TWO_DIMENSION); // We had to aromatize the molecule so that aliphatic related ROs do not match with aromatic compounds. mol.aromatize(MoleculeGraph.AROM_BASIC); } catch (chemaxon.formats.MolFormatException e) { LOGGER.error("Error occurred while trying to import inchi %s: %s", inchi, e.getMessage()); return null; } /* Some ROs depend on multiple copies of a given molecule (like #165), and the Reactor won't run without all of * those molecules available. Duplicate a molecule in the substrates list based on its coefficient in the * reaction. */ Integer coefficient = rxn.getSubstrateCoefficient(id); if (coefficient == null) { // Default to just one if we don't have a clear coefficient to use. LOGGER.warn("Converting coefficient null -> 1 for rxn %d/chem %d", newRxnId, id); coefficient = 1; } for (int i = 0; i < coefficient; i++) { substrateMolecules.add(mol); } } Set<String> expectedProducts = new HashSet<>(); for (Long id : rxn.getProducts()) { String inchi = mapNewChemIdToInChI(id); if (inchi == null) { String msg = String.format("Missing inchi for new chem id %d in cache", id); LOGGER.error(msg); throw new RuntimeException(msg); } if (inchi.contains("FAKE")) { LOGGER.debug("The inchi is a FAKE, so just ignore the chemical."); continue; } String transformedInchi = removeChiralityFromChemical(inchi); if (transformedInchi == null) { return null; } expectedProducts.add(transformedInchi); } TreeMap<Integer, List<Ero>> scoreToListOfRos = new TreeMap<>(Collections.reverseOrder()); for (Map.Entry<Ero, Reactor> entry : reactors.entrySet()) { Integer score = scoreReactionBasedOnRO(entry.getValue(), substrateMolecules, expectedProducts, entry.getKey(), newRxnId); if (score > ROScore.DEFAULT_UNMATCH_SCORE.getScore()) { List<Ero> vals = scoreToListOfRos.get(score); if (vals == null) { vals = new ArrayList<>(); scoreToListOfRos.put(score, vals); } vals.add(entry.getKey()); } } // Cache results for any future similar reactions. cachedEroResults.put(Pair.of(substrateToCoefficientMap, productToCoefficientMap), Pair.of(newRxnId, scoreToListOfRos)); return scoreToListOfRos; }
From source file:gda.scan.ConcurrentScanChild.java
/** * Moves to the next step unless start is true, then moves to the start of the current (possibly child) scan. * @throws Exception// w ww .ja va 2 s . co m */ protected void acquirePoint(boolean start, boolean collectDetectors) throws Exception { TreeMap<Integer, Scannable[]> devicesToMoveByLevel; if (collectDetectors) { devicesToMoveByLevel = generateDevicesToMoveByLevel(scannableLevels, allDetectors); } else { devicesToMoveByLevel = scannableLevels; } for (Integer thisLevel : devicesToMoveByLevel.keySet()) { Scannable[] scannablesAtThisLevel = devicesToMoveByLevel.get(thisLevel); // If there is a detector at this level then wait for detector readout thread to complete for (Scannable scannable : scannablesAtThisLevel) { if (scannable instanceof Detector) { waitForDetectorReadoutAndPublishCompletion(); break; } } checkThreadInterrupted(); // trigger at level start on all Scannables for (Scannable scannable : scannablesAtThisLevel) { scannable.atLevelStart(); } // trigger at level move start on all Scannables for (Scannable scannable : scannablesAtThisLevel) { if (isScannableToBeMoved(scannable) != null) { if (isScannableToBeMoved(scannable).hasStart()) { scannable.atLevelMoveStart(); } } } // on detectors (technically scannables) that implement DetectorWithReadout call waitForReadoutComplete for (Scannable scannable : scannablesAtThisLevel) { if (scannable instanceof DetectorWithReadout) { if (!detectorWithReadoutDeprecationWarningGiven) { logger.warn( "The DetectorWithReadout interface is deprecated. Set gda.scan.concurrentScan.readoutConcurrently to true instead (after reading the 8.24 release note"); detectorWithReadoutDeprecationWarningGiven = true; } ((DetectorWithReadout) scannable).waitForReadoutCompletion(); } } for (Scannable device : scannablesAtThisLevel) { if (!(device instanceof Detector)) { // does this scan (is a hierarchy of nested scans) operate this scannable? ScanObject scanObject = isScannableToBeMoved(device); if (scanObject != null) { if (start) { checkThreadInterrupted(); scanObject.moveToStart(); } else { checkThreadInterrupted(); scanObject.moveStep(); } } } else { if (callCollectDataOnDetectors) { checkThreadInterrupted(); ((Detector) device).collectData(); } } } // pause here until all the scannables at this level have finished moving for (Entry<Integer, Scannable[]> entriesByLevel : devicesToMoveByLevel.entrySet()) { Scannable[] scannablesAtLevel = entriesByLevel.getValue(); for (int i = 0; i < scannablesAtLevel.length; i++) { Scannable scn = scannablesAtLevel[i]; scn.waitWhileBusy(); } } for (Scannable scannable : scannablesAtThisLevel) { scannable.atLevelEnd(); } } }
From source file:org.ecoinformatics.datamanager.database.DatabaseAdapter.java
/** * Assigns database field names to all Attribute objects in the AttributeList. * The assigned field names comply with the following criteria: * (1) each is a legal database field name * (2) each is unique within this attribute list * /* w w w . jav a2s .c om*/ * @param attributeList the AttributeList object containing the Attributes * that correspond to the fields in the database * table */ public void assignDbFieldNames(AttributeList attributeList) { Attribute[] list = attributeList.getAttributes(); TreeMap<String, String> usedNames = new TreeMap<String, String>(); int size = list.length; for (int i = 0; i < size; i++) { Attribute attribute = list[i]; String attributeName = attribute.getName(); String legalDbFieldName = getLegalDbFieldName(attributeName); String foundName = usedNames.get(legalDbFieldName); while (foundName != null) { String mangledName = mangleFieldName(legalDbFieldName); legalDbFieldName = mangledName; foundName = usedNames.get(legalDbFieldName); } usedNames.put(legalDbFieldName, legalDbFieldName); attribute.setDBFieldName(legalDbFieldName); } }
From source file:com.sfs.whichdoctor.dao.SupervisorDAOImpl.java
/** * Ordered supervisors.//from w ww. j a va2 s . c o m * * @param supervisors the supervisors * * @return the collection< supervisor bean> */ private Collection<SupervisorBean> orderedSupervisors(final Collection<SupervisorBean> supervisors) { final Collection<SupervisorBean> ordered = new ArrayList<SupervisorBean>(); TreeMap<String, SupervisorBean> orderMap = new TreeMap<String, SupervisorBean>(); if (supervisors != null) { for (SupervisorBean supervisor : supervisors) { final String key = supervisor.getOrderId() + "_" + supervisor.getGUID(); orderMap.put(key, supervisor); } } int orderId = 1; for (String key : orderMap.keySet()) { SupervisorBean supervisor = orderMap.get(key); supervisor.setOrderId(orderId); ordered.add(supervisor); orderId++; } return ordered; }