List of usage examples for java.util Vector elementAt
public synchronized E elementAt(int index)
From source file:edu.umn.cs.spatialHadoop.core.RTree.java
/** * Builds the RTree given a serialized list of elements. It uses the given * stockObject to deserialize these elements using * {@link TextSerializable#fromText(Text)} and build the tree. Also writes the * created tree to the disk directly.//from w w w .j av a 2s . com * * @param element_bytes * - serialization of all elements separated by new lines * @param offset * - offset of the first byte to use in elements_bytes * @param len * - number of bytes to use in elements_bytes * @param degree * - Degree of the R-tree to build in terms of number of children per * node * @param dataOut * - output stream to write the result to. * @param fast_sort * - setting this to <code>true</code> allows the method to run * faster by materializing the offset of each element in the list * which speeds up the comparison. However, this requires an * additional 16 bytes per element. So, for each 1M elements, the * method will require an additional 16 M bytes (approximately). */ public void bulkLoadWrite(final byte[] element_bytes, final int offset, final int len, final int degree, DataOutput dataOut, final boolean fast_sort) { try { // Count number of elements in the given text int i_start = offset; final Text line = new Text(); while (i_start < offset + len) { int i_end = skipToEOL(element_bytes, i_start); // Extract the line without end of line character line.set(element_bytes, i_start, i_end - i_start - 1); stockObject.fromText(line); elementCount++; i_start = i_end; } LOG.info("Bulk loading an RTree with " + elementCount + " elements"); // It turns out the findBestDegree returns the best degree when the whole // tree is loaded to memory when processed. However, as current algorithms // process the tree while it's on disk, a higher degree should be selected // such that a node fits one file block (assumed to be 4K). //final int degree = findBestDegree(bytesAvailable, elementCount); LOG.info("Writing an RTree with degree " + degree); int height = Math.max(1, (int) Math.ceil(Math.log(elementCount) / Math.log(degree))); int leafNodeCount = (int) Math.pow(degree, height - 1); if (elementCount < 2 * leafNodeCount && height > 1) { height--; leafNodeCount = (int) Math.pow(degree, height - 1); } int nodeCount = (int) ((Math.pow(degree, height) - 1) / (degree - 1)); int nonLeafNodeCount = nodeCount - leafNodeCount; // Keep track of the offset of each element in the text final int[] offsets = new int[elementCount]; final double[] xs = fast_sort ? new double[elementCount] : null; final double[] ys = fast_sort ? new double[elementCount] : null; i_start = offset; line.clear(); for (int i = 0; i < elementCount; i++) { offsets[i] = i_start; int i_end = skipToEOL(element_bytes, i_start); if (xs != null) { // Extract the line with end of line character line.set(element_bytes, i_start, i_end - i_start - 1); stockObject.fromText(line); // Sample center of the shape xs[i] = (stockObject.getMBR().x1 + stockObject.getMBR().x2) / 2; ys[i] = (stockObject.getMBR().y1 + stockObject.getMBR().y2) / 2; } i_start = i_end; } /**A struct to store information about a split*/ class SplitStruct extends Rectangle { /**Start and end index for this split*/ int index1, index2; /**Direction of this split*/ byte direction; /**Index of first element on disk*/ int offsetOfFirstElement; static final byte DIRECTION_X = 0; static final byte DIRECTION_Y = 1; SplitStruct(int index1, int index2, byte direction) { this.index1 = index1; this.index2 = index2; this.direction = direction; } @Override public void write(DataOutput out) throws IOException { out.writeInt(offsetOfFirstElement); super.write(out); } void partition(Queue<SplitStruct> toBePartitioned) { IndexedSortable sortableX; IndexedSortable sortableY; if (fast_sort) { // Use materialized xs[] and ys[] to do the comparisons sortableX = new IndexedSortable() { @Override public void swap(int i, int j) { // Swap xs double tempx = xs[i]; xs[i] = xs[j]; xs[j] = tempx; // Swap ys double tempY = ys[i]; ys[i] = ys[j]; ys[j] = tempY; // Swap id int tempid = offsets[i]; offsets[i] = offsets[j]; offsets[j] = tempid; } @Override public int compare(int i, int j) { if (xs[i] < xs[j]) return -1; if (xs[i] > xs[j]) return 1; return 0; } }; sortableY = new IndexedSortable() { @Override public void swap(int i, int j) { // Swap xs double tempx = xs[i]; xs[i] = xs[j]; xs[j] = tempx; // Swap ys double tempY = ys[i]; ys[i] = ys[j]; ys[j] = tempY; // Swap id int tempid = offsets[i]; offsets[i] = offsets[j]; offsets[j] = tempid; } @Override public int compare(int i, int j) { if (ys[i] < ys[j]) return -1; if (ys[i] > ys[j]) return 1; return 0; } }; } else { // No materialized xs and ys. Always deserialize objects to compare sortableX = new IndexedSortable() { @Override public void swap(int i, int j) { // Swap id int tempid = offsets[i]; offsets[i] = offsets[j]; offsets[j] = tempid; } @Override public int compare(int i, int j) { // Get end of line int eol = skipToEOL(element_bytes, offsets[i]); line.set(element_bytes, offsets[i], eol - offsets[i] - 1); stockObject.fromText(line); double xi = (stockObject.getMBR().x1 + stockObject.getMBR().x2) / 2; eol = skipToEOL(element_bytes, offsets[j]); line.set(element_bytes, offsets[j], eol - offsets[j] - 1); stockObject.fromText(line); double xj = (stockObject.getMBR().x1 + stockObject.getMBR().x2) / 2; if (xi < xj) return -1; if (xi > xj) return 1; return 0; } }; sortableY = new IndexedSortable() { @Override public void swap(int i, int j) { // Swap id int tempid = offsets[i]; offsets[i] = offsets[j]; offsets[j] = tempid; } @Override public int compare(int i, int j) { int eol = skipToEOL(element_bytes, offsets[i]); line.set(element_bytes, offsets[i], eol - offsets[i] - 1); stockObject.fromText(line); double yi = (stockObject.getMBR().y1 + stockObject.getMBR().y2) / 2; eol = skipToEOL(element_bytes, offsets[j]); line.set(element_bytes, offsets[j], eol - offsets[j] - 1); stockObject.fromText(line); double yj = (stockObject.getMBR().y1 + stockObject.getMBR().y2) / 2; if (yi < yj) return -1; if (yi > yj) return 1; return 0; } }; } final IndexedSorter sorter = new QuickSort(); final IndexedSortable[] sortables = new IndexedSortable[2]; sortables[SplitStruct.DIRECTION_X] = sortableX; sortables[SplitStruct.DIRECTION_Y] = sortableY; sorter.sort(sortables[direction], index1, index2); // Partition into maxEntries partitions (equally) and // create a SplitStruct for each partition int i1 = index1; for (int iSplit = 0; iSplit < degree; iSplit++) { int i2 = index1 + (index2 - index1) * (iSplit + 1) / degree; SplitStruct newSplit = new SplitStruct(i1, i2, (byte) (1 - direction)); toBePartitioned.add(newSplit); i1 = i2; } } } // All nodes stored in level-order traversal Vector<SplitStruct> nodes = new Vector<SplitStruct>(); final Queue<SplitStruct> toBePartitioned = new LinkedList<SplitStruct>(); toBePartitioned.add(new SplitStruct(0, elementCount, SplitStruct.DIRECTION_X)); while (!toBePartitioned.isEmpty()) { SplitStruct split = toBePartitioned.poll(); if (nodes.size() < nonLeafNodeCount) { // This is a non-leaf split.partition(toBePartitioned); } nodes.add(split); } if (nodes.size() != nodeCount) { throw new RuntimeException( "Expected node count: " + nodeCount + ". Real node count: " + nodes.size()); } // Now we have our data sorted in the required order. Start building // the tree. // Store the offset of each leaf node in the tree FSDataOutputStream fakeOut = null; try { fakeOut = new FSDataOutputStream(new java.io.OutputStream() { // Null output stream @Override public void write(int b) throws IOException { // Do nothing } @Override public void write(byte[] b, int off, int len) throws IOException { // Do nothing } @Override public void write(byte[] b) throws IOException { // Do nothing } }, null, TreeHeaderSize + nodes.size() * NodeSize); for (int i_leaf = nonLeafNodeCount, i = 0; i_leaf < nodes.size(); i_leaf++) { nodes.elementAt(i_leaf).offsetOfFirstElement = (int) fakeOut.getPos(); if (i != nodes.elementAt(i_leaf).index1) throw new RuntimeException(); double x1, y1, x2, y2; // Initialize MBR to first object int eol = skipToEOL(element_bytes, offsets[i]); fakeOut.write(element_bytes, offsets[i], eol - offsets[i]); line.set(element_bytes, offsets[i], eol - offsets[i] - 1); stockObject.fromText(line); Rectangle mbr = stockObject.getMBR(); x1 = mbr.x1; y1 = mbr.y1; x2 = mbr.x2; y2 = mbr.y2; i++; while (i < nodes.elementAt(i_leaf).index2) { eol = skipToEOL(element_bytes, offsets[i]); fakeOut.write(element_bytes, offsets[i], eol - offsets[i]); line.set(element_bytes, offsets[i], eol - offsets[i] - 1); stockObject.fromText(line); mbr = stockObject.getMBR(); if (mbr.x1 < x1) x1 = mbr.x1; if (mbr.y1 < y1) y1 = mbr.y1; if (mbr.x2 > x2) x2 = mbr.x2; if (mbr.y2 > y2) y2 = mbr.y2; i++; } nodes.elementAt(i_leaf).set(x1, y1, x2, y2); } } finally { if (fakeOut != null) fakeOut.close(); } // Calculate MBR and offsetOfFirstElement for non-leaves for (int i_node = nonLeafNodeCount - 1; i_node >= 0; i_node--) { int i_first_child = i_node * degree + 1; nodes.elementAt(i_node).offsetOfFirstElement = nodes.elementAt(i_first_child).offsetOfFirstElement; int i_child = 0; Rectangle mbr; mbr = nodes.elementAt(i_first_child + i_child); double x1 = mbr.x1; double y1 = mbr.y1; double x2 = mbr.x2; double y2 = mbr.y2; i_child++; while (i_child < degree) { mbr = nodes.elementAt(i_first_child + i_child); if (mbr.x1 < x1) x1 = mbr.x1; if (mbr.y1 < y1) y1 = mbr.y1; if (mbr.x2 > x2) x2 = mbr.x2; if (mbr.y2 > y2) y2 = mbr.y2; i_child++; } nodes.elementAt(i_node).set(x1, y1, x2, y2); } // Start writing the tree // write tree header (including size) // Total tree size. (== Total bytes written - 8 bytes for the size itself) dataOut.writeInt(TreeHeaderSize + NodeSize * nodeCount + len); // Tree height dataOut.writeInt(height); // Degree dataOut.writeInt(degree); dataOut.writeInt(elementCount); // write nodes for (SplitStruct node : nodes) { node.write(dataOut); } // write elements for (int element_i = 0; element_i < elementCount; element_i++) { int eol = skipToEOL(element_bytes, offsets[element_i]); dataOut.write(element_bytes, offsets[element_i], eol - offsets[element_i]); } } catch (IOException e) { e.printStackTrace(); } }
From source file:gov.nih.nci.evs.browser.utils.DataUtils.java
public static Vector sortRelationshipData(Vector relationships, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = "|"; for (int n = 0; n < relationships.size(); n++) { String s = (String) relationships.elementAt(n); Vector ret_vec = parseData(s, "|"); String relationship_name = (String) ret_vec.elementAt(0); String target_concept_name = (String) ret_vec.elementAt(1); String target_concept_code = (String) ret_vec.elementAt(2); String rel_sab = (String) ret_vec.elementAt(3); String key = target_concept_name + delim + relationship_name + delim + target_concept_code + delim + rel_sab;/* w w w .jav a 2s .com*/ if (sortBy.compareTo("source") == 0) { key = rel_sab + delim + target_concept_name + delim + relationship_name + delim + target_concept_code; } else if (sortBy.compareTo("rela") == 0) { key = relationship_name + delim + target_concept_name + delim + target_concept_code + delim + rel_sab; } else if (sortBy.compareTo("code") == 0) { key = target_concept_code + delim + target_concept_name + delim + relationship_name + delim + rel_sab; } hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i = 0; i < key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; }
From source file:gov.nih.nci.evs.browser.utils.DataUtils.java
public static Vector sortSynonymData(Vector synonyms, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = " "; for (int n = 0; n < synonyms.size(); n++) { String s = (String) synonyms.elementAt(n); Vector synonym_data = parseData(s, "|"); String term_name = (String) synonym_data.elementAt(0); String term_type = (String) synonym_data.elementAt(1); String term_source = (String) synonym_data.elementAt(2); String term_source_code = (String) synonym_data.elementAt(3); String cui = (String) synonym_data.elementAt(4); String rel = (String) synonym_data.elementAt(5); String rel_type = (String) synonym_data.elementAt(6); String rel_type_str = getRelationshipCode(rel_type); String key = term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("type") == 0) key = term_type + delim + term_name + delim + term_source + delim + term_source_code + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("source") == 0) key = term_source + delim + term_name + delim + term_type + delim + cui + delim + rel + delim + rel_type_str;/* www . j a v a 2 s . c o m*/ if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_type + delim + term_source + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("rel") == 0) { String rel_key = rel; if (containsAllUpperCaseChars(rel)) rel_key = "|"; key = rel + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui + delim + rel_type_str; } if (sortBy.compareTo("cui") == 0) key = cui + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + rel + delim + rel_type_str; if (sortBy.compareTo("rel_type") == 0) key = rel_type_str + delim + rel + delim + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui; hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i = 0; i < key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; }
From source file:org.ecoinformatics.seek.ecogrid.EcoGridServicesController.java
private SelectableDocumentType[] getDocumentList(ConfigurationProperty cp) { SelectableDocumentType[] documentList = null; Vector documentVector = new Vector(); //NodeList documentTypeNodeList = null; List documentTypeList = cp.getProperties("documentType"); //try {/*from w ww .j a va 2s . c o m*/ // get documenttype node list //documentTypeNodeList = XPathAPI.selectNodeList(serviceNode, // MetadataSpecificationInterface.DOCUMENTTYPE); //} catch (Exception e) { // log.debug("Couldn't find document list in config", e); // return documentList; //}// catch if (documentTypeList == null || documentTypeList.size() == 0) { return documentList; } if (documentTypeList != null && documentTypeList.size() > 0) { int size = documentTypeList.size(); for (int i = 0; i < size; i++) { boolean selected = true; /*Node documentTypeNode = documentTypeNodeList.item(i); String namespace = getKidNodeValue(documentTypeNode, MetadataSpecificationInterface.NAMESPACE); String label = getKidNodeValue(documentTypeNode, MetadataSpecificationInterface.LABEL); String selectedStr = getKidNodeValue(documentTypeNode, MetadataSpecificationInterface.SELECTION); */ ConfigurationProperty documentTypeProp = (ConfigurationProperty) documentTypeList.get(i); String namespace = documentTypeProp.getProperty("namespace").getValue(); String label = documentTypeProp.getProperty("label").getValue(); String selectedStr = documentTypeProp.getProperty("selected").getValue(); // System.out.println("the selection string for namespace // "+namespace+" is "+selectedStr); if (selectedStr != null && selectedStr.equals(FALSE)) { selected = false; } SelectableDocumentType type = null; try { type = new SelectableDocumentType(namespace, label, selected); } catch (Exception e) { log.debug("Couldn't generate a document type", e); continue; } // the vector will stored the document type documentVector.add(type); } // for // transfer a vector to array. int length = documentVector.size(); documentList = new SelectableDocumentType[length]; for (int i = 0; i < length; i++) { documentList[i] = (SelectableDocumentType) documentVector.elementAt(i); } // for } // if return documentList; }
From source file:gov.nih.nci.evs.browser.utils.DataUtils.java
public static String getVisitedConceptLink(Vector concept_vec) { StringBuffer strbuf = new StringBuffer(); String line = "<A href=\"#\" onmouseover=\"Tip('"; strbuf.append(line);/* w ww. j ava 2 s . c o m*/ strbuf.append("<ul>"); for (int i = 0; i < concept_vec.size(); i++) { int j = concept_vec.size() - i - 1; String concept_data = (String) concept_vec.elementAt(j); Vector w = parseData(concept_data, "|"); String scheme = Constants.CODING_SCHEME_NAME; String code = (String) w.elementAt(0); String name = (String) w.elementAt(1); //name = encodeTerm(name); name = encode_term(name); strbuf.append("<li>"); line = "<a href=\\'/ncimbrowser/ConceptReport.jsp?dictionary=" + scheme + "&code=" + code + "\\'>" + name + "</a><br>"; strbuf.append(line); strbuf.append("</li>"); } strbuf.append("</ul>"); line = "',"; strbuf.append(line); line = "WIDTH, 300, TITLE, 'Visited Concepts', SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)\""; strbuf.append(line); line = " onmouseout=UnTip() "; strbuf.append(line); line = ">Visited Concepts</A>"; strbuf.append(line); return strbuf.toString(); }
From source file:com.hexidec.ekit.EkitCore.java
/** * Convenience method for obtaining a custom menu bar *///from w ww .j a va 2s.c o m public JMenuBar getCustomMenuBar(Vector<String> vcMenus) { jMenuBar = new JMenuBar(); for (int i = 0; i < vcMenus.size(); i++) { String menuToAdd = vcMenus.elementAt(i).toLowerCase(); if (htMenus.containsKey(menuToAdd)) { jMenuBar.add((JMenu) (htMenus.get(menuToAdd))); } } return jMenuBar; }
From source file:com.afunms.system.manage.equipManager.java
/** * hostNode MonitorNodeDTO// w w w . ja v a2 s . c o m * * @param hostNode * @return */ public MonitorNodeDTO getMonitorNodeDTOByHostNode(HostNode hostNode) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String date = simpleDateFormat.format(new Date()); String starttime = date + " 00:00:00"; String totime = date + " 23:59:59"; NumberFormat numberFormat = new DecimalFormat(); numberFormat.setMaximumFractionDigits(0); MonitorNodeDTO monitorNodeDTO = null; String ipAddress = hostNode.getIpAddress(); int nodeId = hostNode.getId(); String alias = hostNode.getAlias(); int category = hostNode.getCategory(); if (category == 1) { monitorNodeDTO = new MonitorNetDTO(); monitorNodeDTO.setCategory(""); } else if (category == 4) { monitorNodeDTO = new MonitorHostDTO(); monitorNodeDTO.setCategory(""); } else { monitorNodeDTO = new MonitorNetDTO(); monitorNodeDTO.setCategory(""); } // id monitorNodeDTO.setId(nodeId); // ip monitorNodeDTO.setIpAddress(ipAddress); // monitorNodeDTO.setAlias(alias); Host node = (Host) PollingEngine.getInstance().getNodeByID(nodeId); // if (node != null) { monitorNodeDTO.setStatus(node.getStatus() + ""); } else { monitorNodeDTO.setStatus("0"); } // monitorNodeDTO.setStatus(node.getAlarmlevel() + ""); String cpuValue = "0"; // cpu 0 String memoryValue = "0"; // memory 0 String inutilhdxValue = "0"; // inutilhdx 0 String oututilhdxValue = "0"; // oututilhdx 0 String pingValue = "0"; // ping 0 String eventListCount = ""; // eventListCount 0 String collectType = ""; // String cpuValueColor = "green"; // cpu String memoryValueColor = "green"; // memory String generalAlarm = "0"; // 0 String urgentAlarm = "0"; // 0 String seriousAlarm = "0"; // 0 double cpuValueDouble = 0; double memeryValueDouble = 0; Hashtable eventListSummary = new Hashtable(); Hashtable sharedata = ShareData.getSharedata(); Hashtable ipAllData = (Hashtable) sharedata.get(ipAddress); Hashtable allpingdata = ShareData.getPingdata(); if (ipAllData != null) { Vector cpuV = (Vector) ipAllData.get("cpu"); if (cpuV != null && cpuV.size() > 0) { CPUcollectdata cpu = (CPUcollectdata) cpuV.get(0); if (cpu != null && cpu.getThevalue() != null) { cpuValueDouble = Double.valueOf(cpu.getThevalue()); cpuValue = numberFormat.format(cpuValueDouble); } } Vector memoryVector = (Vector) ipAllData.get("memory"); int allmemoryvalue = 0; if (memoryVector != null && memoryVector.size() > 0) { for (int si = 0; si < memoryVector.size(); si++) { Memorycollectdata memorydata = (Memorycollectdata) memoryVector.elementAt(si); if (memorydata.getEntity().equalsIgnoreCase("Utilization")) { // // if // (memorydata.getSubentity().equalsIgnoreCase("PhysicalMemory")) // { // memeryValueDouble = memeryValueDouble + // Double.valueOf(memorydata.getThevalue()); // } if (category == 4 && memorydata.getSubentity().equalsIgnoreCase("PhysicalMemory")) {// memeryValueDouble = Double.valueOf(memorydata.getThevalue()); } if (category == 1 || category == 2 || category == 3) {// allmemoryvalue = allmemoryvalue + Integer.parseInt(memorydata.getThevalue()); if (si == memoryVector.size() - 1) { memeryValueDouble = allmemoryvalue / memoryVector.size(); } } } } memoryValue = numberFormat.format(memeryValueDouble); } Vector allutil = (Vector) ipAllData.get("allutilhdx"); if (allutil != null && allutil.size() == 3) { AllUtilHdx inutilhdx = (AllUtilHdx) allutil.get(0); inutilhdxValue = inutilhdx.getThevalue(); AllUtilHdx oututilhdx = (AllUtilHdx) allutil.get(1); oututilhdxValue = oututilhdx.getThevalue(); } } if (allpingdata != null) { Vector pingData = (Vector) allpingdata.get(ipAddress); if (pingData != null && pingData.size() > 0) { Pingcollectdata pingcollectdata = (Pingcollectdata) pingData.get(0); pingValue = pingcollectdata.getThevalue(); } } String count = ""; EventListDao eventListDao = new EventListDao(); try { if ("mysql".equalsIgnoreCase(SystemConstant.DBType)) { generalAlarm = eventListDao.getCountByWhere(" where nodeid='" + hostNode.getId() + "'" + " and level1='1' and recordtime>='" + starttime + "' and recordtime<='" + totime + "'"); urgentAlarm = eventListDao.getCountByWhere(" where nodeid='" + hostNode.getId() + "'" + " and level1='2' and recordtime>='" + starttime + "' and recordtime<='" + totime + "'"); seriousAlarm = eventListDao.getCountByWhere(" where nodeid='" + hostNode.getId() + "'" + " and level1='3' and recordtime>='" + starttime + "' and recordtime<='" + totime + "'"); } else if ("oracle".equalsIgnoreCase(SystemConstant.DBType)) { generalAlarm = eventListDao.getCountByWhere( " where nodeid=" + hostNode.getId() + "" + " and level1=1 and recordtime>=to_date('" + starttime + "','YYYY-MM-DD HH24:MI:SS') and recordtime<=to_date('" + totime + "','YYYY-MM-DD HH24:MI:SS')"); urgentAlarm = eventListDao.getCountByWhere( " where nodeid=" + hostNode.getId() + "" + " and level1=2 and recordtime>=to_date('" + starttime + "','YYYY-MM-DD HH24:MI:SS') and recordtime<=to_date('" + totime + "','YYYY-MM-DD HH24:MI:SS')"); seriousAlarm = eventListDao.getCountByWhere( " where nodeid=" + hostNode.getId() + "" + " and level1=3 and recordtime>=to_date('" + starttime + "','YYYY-MM-DD HH24:MI:SS') and recordtime<=to_date('" + totime + "','YYYY-MM-DD HH24:MI:SS')"); } } catch (Exception e) { e.printStackTrace(); } finally { eventListDao.close(); } eventListCount = count; eventListSummary.put("generalAlarm", generalAlarm); eventListSummary.put("urgentAlarm", urgentAlarm); eventListSummary.put("seriousAlarm", seriousAlarm); monitorNodeDTO.setEventListSummary(eventListSummary); if (SystemConstant.COLLECTTYPE_SNMP == hostNode.getCollecttype()) { collectType = "SNMP"; } else if (SystemConstant.COLLECTTYPE_PING == hostNode.getCollecttype()) { collectType = "PING"; } else if (SystemConstant.COLLECTTYPE_REMOTEPING == hostNode.getCollecttype()) { collectType = "REMOTEPING"; } else if (SystemConstant.COLLECTTYPE_SHELL == hostNode.getCollecttype()) { collectType = "SHELL"; } else if (SystemConstant.COLLECTTYPE_SSH == hostNode.getCollecttype()) { collectType = "SSH"; } else if (SystemConstant.COLLECTTYPE_TELNET == hostNode.getCollecttype()) { collectType = "TELNET"; } else if (SystemConstant.COLLECTTYPE_WMI == hostNode.getCollecttype()) { collectType = "WMI"; } NodeMonitorDao nodeMonitorDao = new NodeMonitorDao(); List nodeMonitorList = null; try { nodeMonitorList = nodeMonitorDao.loadByNodeID(nodeId); } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { nodeMonitorDao.close(); } if (nodeMonitorList != null) { for (int j = 0; j < nodeMonitorList.size(); j++) { NodeMonitor nodeMonitor = (NodeMonitor) nodeMonitorList.get(j); if ("cpu".equals(nodeMonitor.getCategory())) { if (cpuValueDouble > nodeMonitor.getLimenvalue2()) { cpuValueColor = "red"; } else if (cpuValueDouble > nodeMonitor.getLimenvalue1()) { cpuValueColor = "orange"; } else if (cpuValueDouble > nodeMonitor.getLimenvalue0()) { cpuValueColor = "yellow"; } else { cpuValueColor = "green"; } } if ("memory".equals(nodeMonitor.getCategory())) { if (memeryValueDouble > nodeMonitor.getLimenvalue2()) { memoryValueColor = "red"; } else if (memeryValueDouble > nodeMonitor.getLimenvalue1()) { memoryValueColor = "orange"; } else if (memeryValueDouble > nodeMonitor.getLimenvalue0()) { memoryValueColor = "yellow"; } else { memoryValueColor = "green"; } } } } monitorNodeDTO.setCpuValue(cpuValue); monitorNodeDTO.setMemoryValue(memoryValue); monitorNodeDTO.setInutilhdxValue(inutilhdxValue); monitorNodeDTO.setOututilhdxValue(oututilhdxValue); monitorNodeDTO.setPingValue(pingValue); monitorNodeDTO.setEventListCount(eventListCount); monitorNodeDTO.setCollectType(collectType); monitorNodeDTO.setCpuValueColor(cpuValueColor); monitorNodeDTO.setMemoryValueColor(memoryValueColor); return monitorNodeDTO; }
From source file:org.adl.samplerte.server.CourseService.java
/** * Updates the list of courses for which a chosen user is registered. * @param iCourseIDs The list of courses that are selected * @param iPath The web path//from w w w .ja v a 2 s.com * @param iUserID The ID of the user. * @return String representation of the success of this action (true or false) */ public String updateRegCourses(Vector iCourseIDs, String iPath, String iUserID) { String result = "true"; mUserID = iUserID; Connection conn; Connection csConn; PreparedStatement stmtSelectCourse; PreparedStatement stmtSelectUserCourse; PreparedStatement stmtInsertUserCourse; PreparedStatement stmtInsertCourseStatus; PreparedStatement stmtDeleteUserCourse; PreparedStatement stmtDeleteCourseStatus; PreparedStatement stmtDeleteCourseObjectives; String sqlSelectUserCourse = "SELECT * FROM UserCourseInfo WHERE UserID = ? AND CourseID = ?"; String sqlSelectCourse = "SELECT * FROM UserCourseInfo WHERE UserID = ?"; String sqlInsertUserCourse = "INSERT INTO UserCourseInfo (UserID, CourseID) VALUES(?,?)"; String sqlDeleteUserCourse = "DELETE FROM UserCourseInfo WHERE UserID = ? AND CourseID = ?"; String sqlInsertCourseStatus = "INSERT INTO CourseStatus (learnerID, courseID) VALUES(?,?)"; String sqlDeleteCourseStatus = "DELETE FROM CourseStatus WHERE learnerID = ? AND courseID = ?"; String sqlDeleteCourseObjectives = "DELETE FROM Objectives WHERE learnerID = ? AND scopeID = ?"; try { conn = LMSDatabaseHandler.getConnection(); csConn = LMSDBHandler.getConnection(); stmtSelectCourse = conn.prepareStatement(sqlSelectCourse); stmtSelectUserCourse = conn.prepareStatement(sqlSelectUserCourse); stmtInsertUserCourse = conn.prepareStatement(sqlInsertUserCourse); stmtDeleteUserCourse = conn.prepareStatement(sqlDeleteUserCourse); stmtInsertCourseStatus = csConn.prepareStatement(sqlInsertCourseStatus); stmtDeleteCourseStatus = csConn.prepareStatement(sqlDeleteCourseStatus); stmtDeleteCourseObjectives = csConn.prepareStatement(sqlDeleteCourseObjectives); SeqActivityTree mySeqActivityTree; //String selectedCourses = "|"; List unregisterCourses = new ArrayList(); RTEFileHandler fileHandler = new RTEFileHandler(); String regTestString = "UN_Course-"; // Process the list of parameters and register for the course if applicable for (int i = 0; i < iCourseIDs.size(); i++) { String paramName = (String) iCourseIDs.elementAt(i); // This is an Unregister request, put this in the unregister list if (paramName.indexOf("RE_Course-") != -1) { unregisterCourses.add(paramName.substring(3, paramName.length())); } int locSkillId = paramName.indexOf(regTestString); if (locSkillId != -1) { String courseID = paramName.substring(3, paramName.length()); ResultSet userCourseRS = null; synchronized (stmtSelectUserCourse) { stmtSelectUserCourse.setString(1, mUserID); stmtSelectUserCourse.setString(2, courseID); userCourseRS = stmtSelectUserCourse.executeQuery(); } if (userCourseRS.next() == false) { synchronized (stmtInsertUserCourse) { stmtInsertUserCourse.setString(1, mUserID); stmtInsertUserCourse.setString(2, courseID); stmtInsertUserCourse.executeUpdate(); } synchronized (stmtInsertCourseStatus) { stmtInsertCourseStatus.setString(1, mUserID); stmtInsertCourseStatus.setString(2, courseID); stmtInsertCourseStatus.executeUpdate(); } String tree = iPath + "CourseImports" + File.separator + courseID + File.separator + "serialize.obj"; FileInputStream in = new FileInputStream(tree); ObjectInputStream ie = new ObjectInputStream(in); mySeqActivityTree = (SeqActivityTree) ie.readObject(); ie.close(); in.close(); // Set the student ID mySeqActivityTree.setLearnerID(mUserID); String scope = mySeqActivityTree.getScopeID(); // Get any global objectives identified in the manifest // from the activity tree. Vector theGobalObjectiveList = mySeqActivityTree.getGlobalObjectives(); if (theGobalObjectiveList != null) { ADLSeqUtilities.createGlobalObjs(mUserID, scope, theGobalObjectiveList); } String userDir = File.separator + SRTEFILESDIR + File.separator + mUserID + File.separator + courseID; File theRTESCODataDir = new File(userDir); // The course directory should not exist yet if (!theRTESCODataDir.isDirectory()) { theRTESCODataDir.mkdirs(); } //Serialize the activity tree out to the user directory String sampleRTERoot = File.separator + SRTEFILESDIR; String serializeFileName = sampleRTERoot + File.separator + mUserID + File.separator + courseID + File.separator + "serialize.obj"; FileOutputStream outFile = new FileOutputStream(serializeFileName); ObjectOutputStream s = new ObjectOutputStream(outFile); s.writeObject(mySeqActivityTree); s.flush(); s.close(); outFile.close(); userCourseRS.close(); } } } Iterator unregIter = unregisterCourses.iterator(); while (unregIter.hasNext()) { String courseID = unregIter.next().toString(); ResultSet userCourseRS = null; synchronized (stmtSelectUserCourse) { stmtSelectUserCourse.setString(1, mUserID); stmtSelectUserCourse.setString(2, courseID); userCourseRS = stmtSelectUserCourse.executeQuery(); } // Look for courses that are not selected for the user if (userCourseRS.next() == true) { synchronized (stmtDeleteUserCourse) { stmtDeleteUserCourse.setString(1, mUserID); stmtDeleteUserCourse.setString(2, courseID); stmtDeleteUserCourse.executeUpdate(); } synchronized (stmtDeleteCourseStatus) { // if adlseq:objectivesGlobalToSystem = "false" in the manifest related to this course // scopeID will be == to courseID and should be removed upon deletion of that course stmtDeleteCourseObjectives.setString(1, mUserID); stmtDeleteCourseObjectives.setString(2, courseID); stmtDeleteCourseObjectives.executeUpdate(); stmtDeleteCourseStatus.setString(1, mUserID); stmtDeleteCourseStatus.setString(2, courseID); stmtDeleteCourseStatus.executeUpdate(); } fileHandler.deleteCourseFiles(courseID, mUserID); } } stmtSelectCourse.close(); stmtSelectUserCourse.close(); stmtInsertUserCourse.close(); stmtDeleteUserCourse.close(); stmtInsertCourseStatus.close(); stmtDeleteCourseStatus.close(); conn.close(); LMSDBHandler.closeConnection(); } catch (Exception e) { result = "false"; } return result; }
From source file:skoa.helpers.Graficos.java
private void aplicarDiferencia(Vector<String> v) { File archivo = new File(ruta + "unificado.txt"); FileReader fr = null;//from w ww . j a v a2s . co m BufferedReader linea = null; String L1, L2, v1 = "", v2 = "", aux1, aux2, line = ""; try { fr = new FileReader(archivo); linea = new BufferedReader(fr); L1 = linea.readLine(); //Lee la primera linea BufferedWriter bw = new BufferedWriter(new FileWriter(ruta + "diferenciaAplicada.txt", true)); //true, para guardar al final del fichero while ((L2 = linea.readLine()) != null) { //y despues la segunda, y hace la diferencia line = L2.substring(0, L2.indexOf("\t")) + "\t"; aux1 = L1.substring(L1.indexOf("\t") + 1);//Quito la fecha aux2 = L2.substring(L2.indexOf("\t") + 1); Boolean coger1 = true, ultimo1 = false, coger2 = true, ultimo2 = false; for (int l = 0; l < v.size(); l++) { if (coger1 & !ultimo1) { //Cojo el valor de la primera linea int p1 = aux1.indexOf("\t"); if (p1 != (-1)) { v1 = aux1.substring(0, p1); aux1 = aux1.substring(p1 + 1); } else { //Ultimo valor. v1 = aux1; aux1 = ""; ultimo1 = true; } } if (coger2 & !ultimo2) { //Cojo el valor de la segunda linea int p1 = aux2.indexOf("\t"); if (p1 != (-1)) { v2 = aux2.substring(0, p1); aux2 = aux2.substring(p1 + 1); } else { //Ultimo valor. v2 = aux2; aux2 = ""; ultimo2 = true; } } String alm1 = v1, alm2 = v2; String u = v.elementAt(l); //Unidad a comparar u = u.substring(u.length() - 1); //Ultimo caracter de la unidad a comparar String u1 = v1.substring(v1.length() - 1); //Ultimo caracter de la unidad de v1 a comparar String u2 = v2.substring(v2.length() - 1); //Ultimo caracter de la unidad de v1 a comparar double x1 = 0, x2 = 0; //Tener en cuenta que el caracter est escrito distinto (no se xq) por lo que hay que tenerlo en cuenta. //Se distinguen 4 posibles casos: v1-v2, v1-0, 0-v2 y 0-0 if (u.compareTo(u1) == 0 | (u.hashCode() == 186 & u1.hashCode() == 176) | (u.compareTo("a") == 0 & (u1.compareTo("a") == 0 | u1.compareTo("A") == 0))) { if (posiblesBooleanos(v1, 0)) x1 = 0; //Comprueba si es booleano negativo else if (posiblesBooleanos(v1, 1)) x1 = 1; //Comprueba si es booleano positivo else { v1 = v1.substring(0, v1.indexOf(" ")); x1 = Double.parseDouble(v1); } if (u.compareTo(u2) == 0 | (u.hashCode() == 186 & u2.hashCode() == 176) | (u.compareTo("a") == 0 & (u2.compareTo("a") == 0 | u2.compareTo("A") == 0))) { //DIFERENCIA v1-v2 if (posiblesBooleanos(v2, 0)) x2 = 0; //Comprueba si es booleano negativo else if (posiblesBooleanos(v2, 1)) x2 = 1; //Comprueba si es booleano positivo else { v2 = v2.substring(0, v2.indexOf(" ")); x2 = Double.parseDouble(v2); } x1 = Math.abs(x1 - x2); //DIFERENCIA v1- v2 coger1 = coger2 = true; } else { //DIFERENCIA v1-0 x1 = Math.abs(x1 - 0); coger1 = true; coger2 = false; } if (posiblesBooleanos(v.elementAt(l), 0) || posiblesBooleanos(v.elementAt(l), 0)) line = line + x1 + " B" + "\t"; //No pongo la unidad else line = line + x1 + " " + v.elementAt(l) + "\t"; } else { //DIFERENCIA 0-v2 if (u.compareTo(u2) == 0 | (u.hashCode() == 186 & u2.hashCode() == 176) | (u.compareTo("a") == 0 & (u2.compareTo("a") == 0 | u2.compareTo("A") == 0))) { if (posiblesBooleanos(v2, 0)) x2 = 0; //Comprueba si es booleano negativo else if (posiblesBooleanos(v2, 1)) x2 = 1; //Comprueba si es booleano positivo else { v2 = v2.substring(0, v2.indexOf(" ")); x2 = Double.parseDouble(v2); } x2 = Math.abs(0 - x2); coger1 = false; coger2 = true; } else { coger1 = coger2 = true; } //DIFERENCIA 0-0 if (posiblesBooleanos(v.elementAt(l), 0) || posiblesBooleanos(v.elementAt(l), 0)) line = line + x1 + " B" + "\t"; //No pongo la unidad else line = line + x2 + " " + v.elementAt(l) + "\t"; } v1 = alm1; v2 = alm2; } bw.write(line + "\n"); L1 = L2; } bw.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != fr) fr.close(); //Se cierra si todo va bien. } catch (Exception e2) { //Sino salta una excepcion. e2.printStackTrace(); } } }
From source file:gov.nih.nci.evs.browser.utils.SourceTreeUtils.java
public ArrayList getIntraCUIRelationships(String scheme, String version, String code, Vector sources, boolean direction, int resolveCodedEntryDepth, int resolveAssociationDepth, boolean keepLastAssociationLevelUnresolved) { ArrayList list = new ArrayList(); if (sources == null || sources.size() == 0) return list; CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version);/* w ww .j ava 2 s . co m*/ long ms = System.currentTimeMillis(); try { CodingScheme cs = null; try { cs = lbSvc.resolveCodingScheme(scheme, csvt); } catch (Exception ex) { ex.printStackTrace(); } if (cs == null) return null; Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); if (hierarchies == null || hierarchies.length == 0) return null; SupportedHierarchy hierarchyDefn = hierarchies[0]; //String hier_id = hierarchyDefn.getLocalId(); String[] associationsToNavigate = hierarchyDefn.getAssociationNames(); boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable(); if (!direction) associationsNavigatedFwd = !associationsNavigatedFwd; CodedNodeSet cns = lbSvc.getNodeSet(scheme, csvt, null); ConceptReferenceList crefs = createConceptReferenceList(new String[] { code }, scheme); cns = cns.restrictToCodes(crefs); NameAndValueList nameAndValueList = createNameAndValueList(associationsToNavigate, null); ResolvedConceptReferenceList matches = null; for (int k = 0; k < sources.size(); k++) { String source = (String) sources.elementAt(k); try { CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList_qualifier = null; if (source != null) { nameAndValueList_qualifier = createNameAndValueList(new String[] { "source" }, new String[] { source }); } cng = cng.restrictToTargetCodes(cns); cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1]; propertyTypes[0] = PropertyType.PRESENTATION; try { matches = cng.resolveAsList(graphFocus, associationsNavigatedFwd, !associationsNavigatedFwd, resolveCodedEntryDepth, resolveAssociationDepth, new LocalNameList(), propertyTypes, null, null, -1, keepLastAssociationLevelUnresolved); } catch (Exception ex) { ex.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); } // Analyze the result ... if (matches == null) { _logger.warn("matches == null ??? "); return list; } if (matches.getResolvedConceptReferenceCount() > 0) { ResolvedConceptReference ref = (ResolvedConceptReference) matches .enumerateResolvedConceptReference().nextElement(); if (ref != null) { AssociationList sourceof = ref.getSourceOf(); if (!associationsNavigatedFwd) sourceof = ref.getTargetOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; if (assoc != null) { String associationName = lbscm.getAssociationNameFromAssociationCode(scheme, csvt, assoc.getAssociationName()); //if (assoc != null) { if (assoc.getAssociatedConcepts() != null) { AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); if (acl != null) { for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; if (ac != null && !ac.getConceptCode().startsWith("@")) { // _logger.debug("\t" + // ac.getCode()); String t = getSelfReferentialRelationship(associationName, ac, source); if (t != null) { // _logger.debug(t); list.add(t); } } } } } //} } } } } } } } } catch (Exception ex) { ex.printStackTrace(); } _logger.debug( "Run time (milliseconds) getSubconcepts: " + (System.currentTimeMillis() - ms) + " to resolve "); // SortUtils.quickSort(list); return list; }