List of usage examples for java.util Hashtable keySet
Set keySet
To view the source code for java.util Hashtable keySet.
Click Source Link
From source file:edu.ku.brc.specify.utilapps.BuildSampleDatabase.java
/** * @param treeDef/*from ww w. ja va 2s . c o m*/ * @param fileName * @param doUserProvidedFile * @return */ public Taxon convertTaxonFromXLS(final TaxonTreeDef treeDef, final String fileName, final boolean doUserProvidedFile) { Hashtable<String, Taxon> taxonHash = new Hashtable<String, Taxon>(); taxonHash.clear(); File file = TaxonLoadSetupPanel.getFileForTaxon(fileName, doUserProvidedFile); if (file == null) { return null; } Vector<TaxonTreeDefItem> rankedItems = new Vector<TaxonTreeDefItem>(); Hashtable<String, Boolean> colNames = new Hashtable<String, Boolean>(); for (TaxonTreeDefItem item : treeDef.getTreeDefItems()) { colNames.put(item.getName().toLowerCase(), true); rankedItems.add(item); } Collections.sort(rankedItems, new Comparator<TaxonTreeDefItem>() { @Override public int compare(TaxonTreeDefItem o1, TaxonTreeDefItem o2) { return o1.getRankId().compareTo(o2.getRankId()); } }); Connection conn = null; Statement stmt = null; TaxonTreeDefItem rootTreeDefItem = rankedItems.get(0); Set<Taxon> rootKids = rootTreeDefItem.getTreeEntries(); Taxon root = rootKids.iterator().next(); Vector<Pair<String, Integer>> nodeList = new Vector<Pair<String, Integer>>(); Pair<String, Integer> rootNode = new Pair<String, Integer>(root.getName(), root.getId()); nodeList.add(rootNode); int counter = 0; int numDataCols = 0; try { startTx(); for (TaxonTreeDefItem item : treeDef.getTreeDefItems()) { persist(item); } persist(root); commitTx(); String[] cells = new String[35]; String[] header = new String[35]; InputStream input = new FileInputStream(file); POIFSFileSystem fs = new POIFSFileSystem(input); HSSFWorkbook workBook = new HSSFWorkbook(fs); HSSFSheet sheet = workBook.getSheetAt(0); Iterator<?> rows = sheet.rowIterator(); int lastRowNum = sheet.getLastRowNum(); if (frame != null) { final int mx = lastRowNum; SwingUtilities.invokeLater(new Runnable() { public void run() { frame.setProcess(0, mx); } }); } conn = DBConnection.getInstance().createConnection(); //conn.setAutoCommit(false); stmt = conn.createStatement(); rows = sheet.rowIterator(); while (rows.hasNext()) { for (int i = 0; i < cells.length; i++) { cells[i] = null; } if (counter == 0) { HSSFRow row = (HSSFRow) rows.next(); Iterator<?> cellsIter = row.cellIterator(); int i = 0; while (cellsIter.hasNext()) { HSSFCell cell = (HSSFCell) cellsIter.next(); if (cell != null) { cells[i] = getXLSCellValueAsStr(cell); header[i] = cells[i]; i++; } } for (i = 0; i < cells.length; i++) { if (cells[i] == null) break; if (colNames.get(cells[i].toLowerCase()) != null) { numDataCols = i + 1; } else { for (String key : colNames.keySet()) { System.err.println("key[" + key + "]"); } System.err.println("Not Found: [" + cells[i].toLowerCase() + "]"); break; } } loadIndexes(cells); counter = 1; for (String hdr : header) { if (hdr == null) break; int inx = 0; for (TaxonTreeDefItem item : rankedItems) { if (hdr.equalsIgnoreCase(item.getName())) { log.debug("Header: " + hdr + " -> " + inx); taxonIndexes.put(hdr, inx); item.setIsInFullName(item.getRankId() >= TaxonTreeDef.GENUS); } else { log.debug("Header: " + hdr + " -> skipped."); } inx++; } } continue; } if (counter % 100 == 0) { if (frame != null) frame.setProcess(counter); //log.info("Converted " + counter + " of "+lastRowNum+" Taxon records"); } HSSFRow row = (HSSFRow) rows.next(); Iterator<?> cellsIter = row.cellIterator(); int i = 0; while (cellsIter.hasNext() && i < cells.length) { HSSFCell cell = (HSSFCell) cellsIter.next(); if (cell != null) { cells[i] = getXLSCellValueAsStr(cell); i++; } } convertTaxonNodes(conn, stmt, header, cells, numDataCols, rootNode, nodeList, rankedItems, root.getDefinition().getId()); counter++; } stmt.executeUpdate( "UPDATE taxon SET IsAccepted = true WHERE IsAccepted IS NULL and AcceptedID IS NULL AND TaxonTReeDefID = " + treeDef.getId()); // Clear all GUIDs in Taxon. stmt.executeUpdate("UPDATE taxon SET GUID = NULL WHERE TaxonTreeDefID = " + treeDef.getId()); conn.close(); input.close(); if (frame != null) frame.setProcess(lastRowNum); root = (Taxon) session.createQuery("FROM Taxon WHERE id = " + root.getId()).list().get(0); } catch (Exception ex) { ex.printStackTrace(); edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BackupServiceFactory.class, ex); } finally { try { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (Exception ex) { ex.printStackTrace(); } } if (frame != null) { frame.setDesc("Saving Taxon Tree..."); frame.getProcessProgress().setIndeterminate(true); } NodeNumberer<Taxon, TaxonTreeDef, TaxonTreeDefItem> nodeNumberer = new NodeNumberer<Taxon, TaxonTreeDef, TaxonTreeDefItem>( root.getDefinition()); nodeNumberer.doInBackground(); //startTx(); //TreeHelper.fixFullnameForNodeAndDescendants(root); //root.setNodeNumber(1); //fixNodeNumbersFromRoot(root); //commitTx(); log.info("Converted " + counter + " Taxon records"); // set up Taxon foreign key mapping for locality taxonHash.clear(); return root; }
From source file:edu.ku.brc.specify.conversion.GenericDBConversion.java
/** * @param treeDef//from w w w . j av a 2s. c om * @throws SQLException */ public void convertGeography(final GeographyTreeDef treeDef, final String dispName, final boolean firstTime) throws SQLException { TableWriter tblWriter = convLogger.getWriter("Geography" + (dispName != null ? dispName : "") + ".html", "Geography"); setTblWriter(tblWriter); IdHashMapper.setTblWriter(tblWriter); if (firstTime) { // empty out any pre-existing records deleteAllRecordsFromTable(newDBConn, "geography", BasicSQLUtils.myDestinationServerType); } IdTableMapper geoIdMapper = (IdTableMapper) IdMapperMgr.getInstance().get("geography", "GeographyID"); if (geoIdMapper == null) { // create an ID mapper for the geography table (mainly for use in converting localities) geoIdMapper = IdMapperMgr.getInstance().addTableMapper("geography", "GeographyID"); } else { geoIdMapper.clearRecords(); } Hashtable<Integer, Geography> oldIdToGeoMap = new Hashtable<Integer, Geography>(); // get a Hibernate session for saving the new records Session localSession = HibernateUtil.getCurrentSession(); HibernateUtil.beginTransaction(); // get all of the old records String sql = "SELECT GeographyID,ContinentOrOcean,Country,State,County,LastEditedBy FROM geography"; Statement statement = oldDBConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); statement.setFetchSize(Integer.MIN_VALUE); ResultSet oldGeoRecords = statement.executeQuery(sql); fixGeography("ContinentOrOcean"); fixGeography("Country"); fixGeography("State"); fixGeography("County"); if (hasFrame) { if (oldGeoRecords.last()) { setProcess(0, oldGeoRecords.getRow()); oldGeoRecords.first(); } } else { oldGeoRecords.first(); } // setup the root Geography record (planet Earth) Geography planetEarth = new Geography(); planetEarth.initialize(); planetEarth.setName("Earth"); planetEarth.setCommonName("Earth"); planetEarth.setRankId(0); planetEarth.setDefinition(treeDef); for (GeographyTreeDefItem defItem : treeDef.getTreeDefItems()) { if (defItem.getRankId() == 0) { planetEarth.setDefinitionItem(defItem); break; } } GeographyTreeDefItem defItem = treeDef.getDefItemByRank(0); planetEarth.setDefinitionItem(defItem); int counter = 0; // for each old record, convert the record do { if (counter % 500 == 0) { if (hasFrame) { setProcess(counter); } else { log.info("Converted " + counter + " geography records"); } } // grab the important data fields from the old record int oldId = oldGeoRecords.getInt(1); String cont = fixSize(tblWriter, oldId, "continent", oldGeoRecords.getString(2), 64); String country = fixSize(tblWriter, oldId, "country", oldGeoRecords.getString(3), 64); String state = fixSize(tblWriter, oldId, "state", oldGeoRecords.getString(4), 64); String county = fixSize(tblWriter, oldId, "county", oldGeoRecords.getString(5), 64); String lastEditedBy = oldGeoRecords.getString(6); Integer agtId = getCreatorAgentId(lastEditedBy); Agent createdByAgent = getCreatedByAgent(localSession, agtId); Agent modifiedByAgent = getAgentObj(localSession, getCurAgentModifierID()); /*cont = isNotEmpty(county) && cont.equals("null") ? null : cont; country = isNotEmpty(country) && country.equals("null") ? null : country; state = isNotEmpty(state) && state.equals("null") ? null : state; county = isNotEmpty(county) && county.equals("null") ? null : county; */ if (isEmpty(cont) && isEmpty(country) && isEmpty(state) && isEmpty(county)) { //String msg = "For Record Id["+oldId+"] Continent, Country, State and County are all null."; //log.error(msg); //tblWriter.logError(msg); cont = "Undefined"; country = "Undefined"; state = "Undefined"; county = "Undefined"; } else if (isEmpty(cont) && isEmpty(country) && isEmpty(state)) { //String msg = "For Record Id["+oldId+"] Continent, Country and State are all null."; //log.error(msg); //tblWriter.logError(msg); cont = "Undefined"; country = "Undefined"; state = "Undefined"; } else if (isEmpty(cont) && isEmpty(country)) { //String msg = "For Record Id["+oldId+"] Country is null."; //log.error(msg); //tblWriter.logError(msg); cont = "Undefined"; country = "Undefined"; } else if (isEmpty(cont)) { //String msg = "For Record Id["+oldId+"] Country is null."; //log.error(msg); //tblWriter.logError(msg); cont = "Undefined"; } // create a new Geography object from the old data List<Geography> newGeos = convertOldGeoRecord(cont, country, state, county, createdByAgent, modifiedByAgent, planetEarth); if (newGeos.size() > 0) { Geography lowestLevel = newGeos.get(newGeos.size() - 1); oldIdToGeoMap.put(oldId, lowestLevel); } counter++; } while (oldGeoRecords.next()); if (hasFrame) { setProcess(counter); } else { log.info("Converted " + counter + " geography records"); } TreeHelper.fixFullnameForNodeAndDescendants(planetEarth); planetEarth.setNodeNumber(1); fixNodeNumbersFromRoot(planetEarth); localSession.save(planetEarth); HibernateUtil.commitTransaction(); log.info("Converted " + counter + " geography records"); if (shouldCreateMapTables) { // add all of the ID mappings for (Integer oldId : oldIdToGeoMap.keySet()) { Geography geo = oldIdToGeoMap.get(oldId); geoIdMapper.put(oldId, geo.getId()); } } if (firstTime) { // set up Geography foreign key mapping for locality idMapperMgr.mapForeignKey("Locality", "GeographyID", "Geography", "GeographyID"); } }
From source file:org.sakaiproject.site.tool.SiteAction.java
private void importToolIntoSiteMigrate(List toolIds, Hashtable importTools, Site site) { if (importTools != null) { //if add missing tools is enabled, add the tools ito the site before importing content if (isAddMissingToolsOnImportEnabled()) { //add the toolId lists into a set to remove dupes Set<String> toolsToProcess = new HashSet<String>(toolIds); toolsToProcess.addAll(importTools.keySet()); //now compare what we have to what we need to add final List<String> selectedTools = new ArrayList<String>(toolsToProcess); M_log.debug("selectedTools: " + selectedTools); List<String> missingToolIds = new ArrayList<String>(selectedTools); missingToolIds.removeAll(toolIds); M_log.debug("missingToolIds: " + missingToolIds); //and add for (String missingToolId : missingToolIds) { site = addToolToSiteIfMissing(site, missingToolId); commitSite(site);//from w ww .j a v a 2 s . com } } Map transversalMap = new HashMap(); // import resources first boolean resourcesImported = false; for (int i = 0; i < toolIds.size() && !resourcesImported; i++) { String toolId = (String) toolIds.get(i); if (toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); String fromSiteCollectionId = m_contentHostingService.getSiteCollection(fromSiteId); String toSiteCollectionId = m_contentHostingService.getSiteCollection(toSiteId); Map<String, String> entityMap = transferCopyEntitiesMigrate(toolId, fromSiteCollectionId, toSiteCollectionId); if (entityMap != null) { transversalMap.putAll(entityMap); } resourcesImported = true; } } } // import other tools then for (int i = 0; i < toolIds.size(); i++) { String toolId = (String) toolIds.get(i); if (!toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); if (SITE_INFO_TOOL_ID.equals(toolId)) { copySiteInformation(fromSiteId, site); } else { Map<String, String> entityMap = transferCopyEntitiesMigrate(toolId, fromSiteId, toSiteId); if (entityMap != null) { transversalMap.putAll(entityMap); } } } } } //update entity references for (int i = 0; i < toolIds.size(); i++) { String toolId = (String) toolIds.get(i); if (importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String toSiteId = site.getId(); updateEntityReferences(toolId, toSiteId, transversalMap, site); } } } } }
From source file:org.sakaiproject.site.tool.SiteAction.java
/** * Import tools and content into the site * /*from ww w . jav a 2 s . c o m*/ * If the isAddMissingToolsOnImportEnabled setting is true, tools that are selected for import and don't already exist in the target site will be added automatically. * * @param toolIds list of tools already in the site * @param importTools list of tools that were selected for import * @param site the site to import content into */ private void importToolIntoSite(List toolIds, Hashtable importTools, Site site) { if (importTools != null) { //if add missing tools is enabled, add the tools ito the site before importing content if (isAddMissingToolsOnImportEnabled()) { //add the toolId lists into a set to remove dupes Set<String> toolsToProcess = new HashSet<String>(toolIds); toolsToProcess.addAll(importTools.keySet()); //now compare what we have to what we need to add final List<String> selectedTools = new ArrayList<String>(toolsToProcess); M_log.debug("selectedTools: " + selectedTools); List<String> missingToolIds = new ArrayList<String>(selectedTools); missingToolIds.removeAll(toolIds); M_log.debug("missingToolIds: " + missingToolIds); //and add for (String missingToolId : missingToolIds) { site = addToolToSiteIfMissing(site, missingToolId); commitSite(site); } //now update toolIds to match importTools so that the content is imported toolIds.clear(); toolIds.addAll(importTools.keySet()); } Map transversalMap = new HashMap(); // import resources first boolean resourcesImported = false; for (int i = 0; i < toolIds.size() && !resourcesImported; i++) { String toolId = (String) toolIds.get(i); if (toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); String fromSiteCollectionId = m_contentHostingService.getSiteCollection(fromSiteId); String toSiteCollectionId = m_contentHostingService.getSiteCollection(toSiteId); Map<String, String> entityMap = transferCopyEntities(toolId, fromSiteCollectionId, toSiteCollectionId); if (entityMap != null) { transversalMap.putAll(entityMap); } resourcesImported = true; } } } // import other tools then for (int i = 0; i < toolIds.size(); i++) { String toolId = (String) toolIds.get(i); if (!toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); if (SITE_INFO_TOOL_ID.equals(toolId)) { copySiteInformation(fromSiteId, site); } else { Map<String, String> entityMap = transferCopyEntities(toolId, fromSiteId, toSiteId); if (entityMap != null) { transversalMap.putAll(entityMap); } resourcesImported = true; } } } } //update entity references for (int i = 0; i < toolIds.size(); i++) { String toolId = (String) toolIds.get(i); if (importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String toSiteId = site.getId(); updateEntityReferences(toolId, toSiteId, transversalMap, site); } } } } }
From source file:com.globalsight.webservices.Ambassador.java
private void changeFileListByXliff(String p_filename, String p_targetLocale, FileProfile p_fileProfile, Vector p_fileProfileList, Vector p_fileList, Vector p_afterTargetLocales) { Hashtable<String, FileProfile> splitFiles = new Hashtable<String, FileProfile>(); XliffFileUtil.processMultipleFileTags(splitFiles, p_filename, p_fileProfile); if (splitFiles != null && splitFiles.size() > 0) { for (Iterator<String> iterator = splitFiles.keySet().iterator(); iterator.hasNext();) { String tmp = iterator.next(); p_fileList.add(new File(AmbFileStoragePathUtils.getCxeDocDir(), tmp)); p_fileProfileList.add(p_fileProfile); p_afterTargetLocales.add(p_targetLocale); }/*from w ww . j av a 2 s. co m*/ } }
From source file:com.globalsight.webservices.Ambassador.java
/** * Generate workflow info in xml format/* w w w .j a v a 2s. c o m*/ * * @param workflow * workflow object * @param tab * Tab string as prefix, such as '\t\t' * @return String workflow info in xml format */ private String getWorkflowInfo(Workflow workflow, String tab) { StringBuilder xml = new StringBuilder(); TaskInstance taskInstance = null; // workflow xml.append(tab).append("<workflow>\r\n"); // workflow id xml.append(tab).append("\t<workflow_id>").append(workflow.getId()).append("</workflow_id>\r\n"); // workflow state xml.append(tab).append("\t<workflow_state>").append(workflow.getState()).append("</workflow_state>\r\n"); xml.append(tab).append("\t<target_locale>").append(workflow.getTargetLocale()) .append("</target_locale>\r\n"); xml.append(tab).append("\t<dispatch_date>") .append(workflow.getDispatchedDate() == null ? "" : DateHelper.getFormattedDateAndTime(workflow.getDispatchedDate(), null)) .append("</dispatch_date>\r\n"); // tasks Hashtable<Long, Task> tasks = (Hashtable<Long, Task>) workflow.getTasks(); Rate rate = null; if (tasks == null || tasks.size() == 0) { xml.append(tab).append("\t<tasks>\r\n").append(tab).append("\t</tasks>\r\n"); } else { xml.append(tab).append("\t<tasks>\r\n"); // each task Long taskId = null; Task task = null; String tmp = ""; for (Iterator<Long> ids = tasks.keySet().iterator(); ids.hasNext();) { taskId = ids.next(); // task = tasks.get(taskId); try { task = ServerProxy.getTaskManager().getTask(taskId); } catch (Exception e) { } tmp = getTaskInfo(task, tab + "\t\t"); xml.append(tmp); } xml.append(tab).append("\t</tasks>\r\n"); } // current activity taskInstance = WorkflowManagerLocal.getCurrentTask(workflow.getId()); String currentTaskName = ""; if (taskInstance != null) { currentTaskName = TaskJbpmUtil.getTaskDisplayName(taskInstance.getName()); xml.append(tab).append("\t<current_activity>").append(currentTaskName) .append("</current_activity>\r\n"); } /** Wordcount Summary */ xml.append(tab).append("\t<word_counts>\r\n"); // leverageOption String leverageOption = "unknown"; boolean isInContextMatch = false; try { Job job = workflow.getJob(); if (PageHandler.isInContextMatch(job)) { isInContextMatch = true; } if (isInContextMatch) { leverageOption = "Leverage in context matches"; } else { leverageOption = "100% match only"; } } catch (Exception e) { } xml.append(tab).append("\t\t<leverage_option>").append(leverageOption).append("</leverage_option>\r\n"); // 100% int wc = 0; if (isInContextMatch) { wc = workflow.getSegmentTmWordCount(); } else { wc = workflow.getTotalExactMatchWordCount(); } xml.append(tab).append("\t\t<match_100_percent>").append(wc).append("</match_100_percent>\r\n"); // 95%-99% xml.append(tab).append("\t\t<match_95_percent-99_percent>").append(workflow.getThresholdHiFuzzyWordCount()) .append("</match_95_percent-99_percent>\r\n"); // 85%-94% xml.append(tab).append("\t\t<match_85_percent-94_percent>") .append(workflow.getThresholdMedHiFuzzyWordCount()).append("</match_85_percent-94_percent>\r\n"); // 75%-84% xml.append(tab).append("\t\t<match_75_percent-84_percent>").append(workflow.getThresholdMedFuzzyWordCount()) .append("</match_75_percent-84_percent>\r\n"); // noMatch (50%-74%) xml.append(tab).append("\t\t<no_match>") .append(workflow.getThresholdNoMatchWordCount() + workflow.getThresholdLowFuzzyWordCount()) .append("</no_match>\r\n"); // Repetitions xml.append(tab).append("\t\t<repetitions>").append(workflow.getRepetitionWordCount()) .append("</repetitions>\r\n"); // In Context Matches if (isInContextMatch) { xml.append(tab).append("\t\t<in_context_matches>").append(workflow.getInContextMatchWordCount()) .append("</in_context_matches>\r\n"); } // total xml.append(tab).append("\t\t<total>").append(workflow.getTotalWordCount()).append("</total>\r\n"); xml.append(tab).append("\t</word_counts>\r\n"); if (workflow.getCompletedDate() != null) { xml.append(tab).append("\t<complete_date>") .append(DateHelper.getFormattedDateAndTime(workflow.getCompletedDate(), null)) .append("</complete_date>\r\n"); } xml.append(tab).append("</workflow>\r\n"); return xml.toString(); }
From source file:edu.ku.brc.specify.conversion.GenericDBConversion.java
/** * @param tblWriter/* w ww. java2 s .co m*/ * @param treeDef * @param isPaleo * @throws SQLException */ public void convertGTP(final TableWriter tblWriter, final GeologicTimePeriodTreeDef treeDef, final boolean isPaleo) throws SQLException { deleteAllRecordsFromTable("geologictimeperiod", BasicSQLUtils.myDestinationServerType); log.info("Converting old geologic time period records"); int count = 0; // create an ID mapper for the geologictimeperiod table IdTableMapper gtpIdMapper = IdMapperMgr.getInstance().addTableMapper("geologictimeperiod", "GeologicTimePeriodID"); Hashtable<Integer, GeologicTimePeriod> oldIdToGTPMap = new Hashtable<Integer, GeologicTimePeriod>(); // String sql = "SELECT g.GeologicTimePeriodID,g.RankCode,g.Name,g.Standard,g.Remarks,g.TimestampModified,g.TimestampCreated,p1.Age as Upper," + // "p1.AgeUncertainty as UpperUncertainty,p2.Age as Lower,p2.AgeUncertainty as LowerUncertainty FROM geologictimeperiod g, " + // "geologictimeboundary p1, geologictimeboundary p2 WHERE g.UpperBoundaryID=p1.GeologicTimeBoundaryID AND " + // "g.LowerBoundaryID=p2.GeologicTimeBoundaryID ORDER BY Lower DESC, RankCode"; String sql = "SELECT g.GeologicTimePeriodID,g.RankCode,g.Name,g.Standard,g.Remarks,g.TimestampModified,g.TimestampCreated,gb1.Age as Upper," + "gb1.AgeUncertainty as UpperUncertainty,gb2.Age as Lower,gb2.AgeUncertainty as LowerUncertainty FROM geologictimeperiod g " + "LEFT OUTER JOIN geologictimeboundary gb1 ON g.UpperBoundaryID = gb1.GeologicTimeBoundaryID " + "LEFT OUTER JOIN geologictimeboundary gb2 ON g.LowerBoundaryID = gb2.GeologicTimeBoundaryID " + "ORDER BY Lower DESC, RankCode"; Statement statement = oldDBConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); statement.setFetchSize(Integer.MIN_VALUE); ResultSet rs = statement.executeQuery(sql); Session localSession = HibernateUtil.getCurrentSession(); HibernateUtil.beginTransaction(); Vector<GeologicTimePeriod> newItems = new Vector<GeologicTimePeriod>(); GeologicTimePeriod allTime = new GeologicTimePeriod(); allTime.initialize(); allTime.setDefinition(treeDef); GeologicTimePeriodTreeDefItem rootDefItem = treeDef.getDefItemByRank(0); allTime.setDefinitionItem(rootDefItem); allTime.setRankId(0); allTime.setName("Time"); allTime.setFullName("Time"); allTime.setStartPeriod(100000f); allTime.setEndPeriod(0f); allTime.setEndUncertainty(0f); allTime.setTimestampCreated(now); ++count; newItems.add(allTime); ArrayList<GeologicTimePeriod> needsPlaceHolderList = new ArrayList<GeologicTimePeriod>(); boolean needsTbl = true; if (isPaleo) { while (rs.next()) { Integer id = rs.getInt(1); Integer rank = rs.getInt(2) * 100; String name = rs.getString(3); String std = rs.getString(4); String rem = rs.getString(5); Date modTDate = rs.getDate(6); Date creTDate = rs.getDate(7); Timestamp modT = (modTDate != null) ? new Timestamp(modTDate.getTime()) : null; Timestamp creT = (creTDate != null) ? new Timestamp(creTDate.getTime()) : null; Float upper = (Float) rs.getObject(8); Float uError = (Float) rs.getObject(9); Float lower = (Float) rs.getObject(10); Float lError = (Float) rs.getObject(11); if (isEmpty(name)) { if (needsTbl) { tblWriter.startTable(); tblWriter.logHdr("ID", "Rank Name", "Name", "Reason"); needsTbl = false; } tblWriter.log(id.toString(), rank.toString(), name, "Name is null, Name set to 'XXXX'"); log.error("The Name is empty (or null) for GTP ID[" + id + "] Rank[" + rank + "]"); name = "XXXX"; } if (modT == null && creT == null) { creT = now; modT = now; } else if (modT == null && creT != null) { modT = new Timestamp(creT.getTime()); } else if (modT != null && creT == null) { creT = new Timestamp(modT.getTime()); } // else (neither are null, so do nothing) GeologicTimePeriodTreeDefItem defItem = rank != null ? treeDef.getDefItemByRank(rank) : null; GeologicTimePeriod gtp = new GeologicTimePeriod(); gtp.initialize(); gtp.setName(name); gtp.setFullName(name); gtp.setDefinitionItem(defItem); gtp.setRankId(rank); gtp.setDefinition(treeDef); gtp.setStartPeriod(lower); gtp.setStartUncertainty(lError); gtp.setEndPeriod(upper); gtp.setEndUncertainty(uError); gtp.setStandard(std); gtp.setRemarks(rem); gtp.setTimestampCreated(creT); gtp.setTimestampModified(modT); if (lower == null || upper == null || rank == null) { needsPlaceHolderList.add(gtp); log.debug("PlaceHold Old ID: " + id); } else { newItems.add(gtp); } oldIdToGTPMap.put(id, gtp); if (++count % 500 == 0) { log.info(count + " geologic time period records converted"); } } // now we need to fix the parent/pointers for (int i = 0; i < newItems.size(); ++i) { GeologicTimePeriod gtp = newItems.get(i); for (int j = 0; j < newItems.size(); ++j) { GeologicTimePeriod child = newItems.get(j); if (isParentChildPair(gtp, child)) { gtp.addChild(child); } } } if (needsPlaceHolderList.size() > 0) { int rank = 100; for (GeologicTimePeriodTreeDefItem di : treeDef.getTreeDefItems()) { System.out.println(di.getName() + " -> " + di.getRankId()); } GeologicTimePeriodTreeDefItem defItem = treeDef.getDefItemByRank(rank); GeologicTimePeriod gtp = new GeologicTimePeriod(); gtp.initialize(); gtp.setName("Placeholder"); gtp.setFullName("Placeholder"); gtp.setDefinitionItem(defItem); gtp.setRankId(rank); gtp.setDefinition(treeDef); gtp.setStartPeriod(0.0f); gtp.setStartUncertainty(0.0f); gtp.setEndPeriod(0.0f); gtp.setEndUncertainty(0.0f); gtp.setStandard(null); gtp.setRemarks(null); gtp.setTimestampCreated(now); gtp.setTimestampModified(now); allTime.addChild(gtp); rank = 200; defItem = treeDef.getDefItemByRank(rank); for (GeologicTimePeriod gtpPH : needsPlaceHolderList) { gtpPH.setDefinition(treeDef); gtpPH.setDefinitionItem(defItem); gtpPH.setRankId(rank); gtpPH.setStartPeriod(0.0f); gtpPH.setStartUncertainty(0.0f); gtpPH.setEndPeriod(0.0f); gtpPH.setEndUncertainty(0.0f); gtp.addChild(gtpPH); } } TreeHelper.fixFullnameForNodeAndDescendants(allTime); } // fix node number, child node number stuff allTime.setNodeNumber(1); fixNodeNumbersFromRoot(allTime); localSession.save(allTime); HibernateUtil.commitTransaction(); if (shouldCreateMapTables) { // add all of the ID mappings for (Integer oldId : oldIdToGTPMap.keySet()) { if (oldId != null) { GeologicTimePeriod gtp = oldIdToGTPMap.get(oldId); if (gtp != null) { if (gtp.getId() != null) { gtpIdMapper.put(oldId, gtp.getId()); } else { log.debug("GTP id is null: " + gtp.getName()); } } else { log.debug("GTP missing in hash for Old ID: " + oldId); } } else { log.debug("Old ID in Hash is null: " + oldId); } } } // set up geologictimeperiod foreign key mapping for stratigraphy IdMapperMgr.getInstance().mapForeignKey("Stratigraphy", "GeologicTimePeriodID", "GeologicTimePeriod", "GeologicTimePeriodID"); log.info(count + " geologic time period records converted"); if (!needsTbl) { tblWriter.endTable(); } }
From source file:com.afunms.report.abstraction.ExcelReport1.java
public void createReport_hostall(String filename) { if (impReport.getTable() == null) { fileName = null;/* www . j av a 2 s . c o m*/ return; } WritableWorkbook wb = null; try { // fileName = ResourceCenter.getInstance().getSysPath() + // "temp\\dhcnms_report.xls"; fileName = ResourceCenter.getInstance().getSysPath() + filename; wb = Workbook.createWorkbook(new File(fileName)); Hashtable allreporthash = new Hashtable(); allreporthash = reportHash; if (allreporthash != null && allreporthash.size() > 0) { Iterator keys = allreporthash.keySet().iterator(); String ip = ""; int sheetNum = 0; while (keys.hasNext()) { ip = keys.next().toString(); Hashtable report_has = (Hashtable) allreporthash.get(ip); String hostname = (String) report_has.get("equipname"); WritableSheet sheet = wb.createSheet(hostname + "", sheetNum); this.createReportTitle(sheet, report_has); this.createPingAndCpu(sheet, ip, report_has); this.createMemory(sheet, ip, report_has); this.createDisk(sheet, ip, report_has); sheetNum++; } wb.write(); } } catch (Exception e) { // SysLogger.error("Error in ExcelReport.createReport()",e); SysLogger.error("", e); } finally { try { if (wb != null) wb.close(); } catch (Exception e) { } } }
From source file:com.afunms.report.abstraction.ExcelReport1.java
/** * @author HONGLI DB2 xls/*from w w w . ja v a 2 s .co m*/ * @param filename * @throws DocumentException * @throws IOException */ public void createReportDB2SelfExcel(String filename) { if (impReport.getTable() == null) { fileName = null; return; } WritableWorkbook wb = null; try { // fileName = ResourceCenter.getInstance().getSysPath() + // "temp\\dhcnms_report.xls"; // fileName = CommonAppUtil.getAppName() + // "/temp/hostnms_report.xls"; fileName = ResourceCenter.getInstance().getSysPath() + filename; wb = Workbook.createWorkbook(new File(fileName)); String hostname = (String) reportHash.get("dbname"); String ip = (String) reportHash.get("ip"); String newip = doip(ip); WritableSheet sheet = wb.createSheet(hostname + "", 0); String Ping = (String) reportHash.get("Ping"); String starttime = (String) reportHash.get("starttime"); String totime = (String) reportHash.get("totime"); Hashtable maxping = (Hashtable) reportHash.get("ping"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); WritableFont labelFont = new WritableFont(WritableFont.createFont(""), 12, WritableFont.BOLD, false); WritableCellFormat labelFormat = new WritableCellFormat(labelFont); WritableCellFormat _labelFormat = new WritableCellFormat(); _labelFormat.setBackground(jxl.format.Colour.GRAY_25); WritableCellFormat p_labelFormat = new WritableCellFormat(); p_labelFormat.setBackground(jxl.format.Colour.ICE_BLUE); WritableCellFormat b_labelFormat = new WritableCellFormat(); b_labelFormat.setBackground(jxl.format.Colour.GRAY_50); Label tmpLabel = null; tmpLabel = new Label(1, 0, hostname + "", labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(0, 1, ":" + impReport.getTimeStamp()); sheet.addCell(tmpLabel); tmpLabel = new Label(0, 2, ": " + starttime + " " + totime); sheet.addCell(tmpLabel); tmpLabel = new Label(0, 4, "", b_labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(1, 4, "", _labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(2, 4, "", _labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(0, 5, (String) maxping.get("pingnow"), p_labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(1, 5, (String) maxping.get("pingmax"), p_labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(2, 5, (String) maxping.get("avgpingcon"), p_labelFormat); sheet.addCell(tmpLabel); // File file = new File(ResourceCenter.getInstance().getSysPath() + "/resource/image/jfreechart/" + newip + "ConnectUtilization" + ".png"); // sheet,0,0,5,1,,, // allRow = allRow+2; sheet.addImage(new WritableImage(1, 6, 7, 7, file)); // allRow = allRow+7; tmpLabel = new Label(0, 14, "", b_labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(1, 14, "", b_labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(2, 14, "(MB)", _labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(3, 14, "(MB)", _labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(4, 14, "(%)", _labelFormat); sheet.addCell(tmpLabel); int row = 14; // Hashtable spaceInfo = (Hashtable) reportHash.get("spaceInfo"); Iterator iterator = spaceInfo.keySet().iterator(); while (iterator.hasNext()) { String dbName = (String) iterator.next(); List toolsdb = (ArrayList) spaceInfo.get(dbName); if (toolsdb != null && toolsdb.size() > 0) { for (int i = 0; i < toolsdb.size(); i++) { Hashtable tempSpace = (Hashtable) toolsdb.get(i); String SYSCATSPACE = tempSpace.get("tablespace_name") + ""; String totalspac = tempSpace.get("totalspac") + ""; String usablespac = tempSpace.get("usablespac") + ""; String usableper = (String) tempSpace.get("usableper"); if (usableper == null || usableper.trim().equals("")) { usableper = "0"; } row = row + 1; tmpLabel = new Label(0, row, i + 1 + "", p_labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(1, row, SYSCATSPACE, p_labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(2, row, totalspac, p_labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(3, row, usablespac, p_labelFormat); sheet.addCell(tmpLabel); tmpLabel = new Label(4, row, usableper, p_labelFormat); sheet.addCell(tmpLabel); } } } if (impReport.getChart() != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ChartUtilities.writeChartAsPNG(baos, impReport.getChart().getChart(), impReport.getChart().getWidth(), impReport.getChart().getHeight()); } catch (IOException ioe) { } WritableImage wi = new WritableImage(2, 10000 + 5, 8, 12, baos.toByteArray()); sheet.addImage(wi); } wb.write(); } catch (Exception e) { // SysLogger.error("Error in ExcelReport.createReport()",e); SysLogger.error("", e); } finally { try { if (wb != null) wb.close(); } catch (Exception e) { } } }
From source file:com.afunms.report.abstraction.ExcelReport1.java
/** * @author HONGLI DB2 pdf/*from w w w . ja va2 s . c o m*/ * @param filename * @throws DocumentException * @throws IOException */ public void createReportDB2SelfPdf(String filename) throws DocumentException, IOException { if (impReport.getTable() == null) { fileName = null; return; } try { // Document document = new Document(PageSize.A4); // (Writer)document(Writer) PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); // BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); // Font titleFont = new Font(bfChinese, 12, Font.BOLD); // Font contextFont = new Font(bfChinese, 12, Font.NORMAL); String hostname = (String) reportHash.get("dbname"); String ip = (String) reportHash.get("ip"); String newip = doip(ip); Paragraph title = new Paragraph(hostname + "", titleFont); // title.setAlignment(Element.ALIGN_CENTER); // title.setFont(titleFont); document.add(title); String Ping = (String) reportHash.get("Ping"); String starttime = (String) reportHash.get("starttime"); String totime = (String) reportHash.get("totime"); Hashtable maxping = (Hashtable) reportHash.get("ping"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String contextString = ":" + impReport.getTimeStamp() + " \n"// + ":" + starttime + " " + totime; Paragraph context = new Paragraph(contextString, contextFont); // context.setAlignment(Element.ALIGN_LEFT); // context.setFont(contextFont); // context.setSpacingBefore(5); // context.setFirstLineIndent(5); document.add(context); document.add(new Paragraph("\n")); /* * tmpLabel = new Label(0, 1, ":" + impReport.getTimeStamp()); * sheet.addCell(tmpLabel); tmpLabel = new Label(0, 2, ": " + * starttime + " " + totime); */ PdfPTable aTable = new PdfPTable(3); float[] widths = { 220f, 220f, 220f }; aTable.setWidths(widths); aTable.setWidthPercentage(100); PdfPCell cell = null; cell = new PdfPCell(new Phrase("", titleFont)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable.addCell(cell); cell = new PdfPCell(new Phrase("", titleFont)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable.addCell(cell); cell = new PdfPCell(new Phrase("", titleFont)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable.addCell(cell); cell = new PdfPCell(new Phrase((String) maxping.get("pingnow"))); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable.addCell(cell); cell = new PdfPCell(new Phrase((String) maxping.get("pingmax"))); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable.addCell(cell); cell = new PdfPCell(new Phrase((String) maxping.get("avgpingcon"))); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable.addCell(cell); Image img = Image.getInstance(ResourceCenter.getInstance().getSysPath() + "/resource/image/jfreechart/" + newip + "ConnectUtilization" + ".png"); img.setAlignment(Image.LEFT);// // document.add(aTable); img.scalePercent(76); document.add(aTable); document.add(img); document.add(new Paragraph("\n")); PdfPTable aTable1 = new PdfPTable(5); float[] width = { 220f, 220f, 220f, 220f, 220f }; aTable1.setWidths(width); aTable1.setWidthPercentage(100); cell = new PdfPCell(new Phrase("", titleFont)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable1.addCell(cell); cell = new PdfPCell(new Phrase("", titleFont)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable1.addCell(cell); cell = new PdfPCell(new Phrase("(MB)", titleFont)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable1.addCell(cell); cell = new PdfPCell(new Phrase("(MB)", titleFont)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable1.addCell(cell); cell = new PdfPCell(new Phrase("(%)", titleFont)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable1.addCell(cell); // aTable1.endHeaders(); // Hashtable spaceInfo = (Hashtable) reportHash.get("spaceInfo"); Iterator iterator = spaceInfo.keySet().iterator(); while (iterator.hasNext()) { String dbName = (String) iterator.next(); List toolsdb = (ArrayList) spaceInfo.get(dbName); if (toolsdb != null && toolsdb.size() > 0) { for (int i = 0; i < toolsdb.size(); i++) { Hashtable tempSpace = (Hashtable) toolsdb.get(i); String SYSCATSPACE = tempSpace.get("tablespace_name") + ""; String totalspac = tempSpace.get("totalspac") + ""; String usablespac = tempSpace.get("usablespac") + ""; String usableper = (String) tempSpace.get("usableper"); if (usableper == null || usableper.trim().equals("")) { usableper = "0"; } cell = new PdfPCell(new Phrase((i + 1) + "")); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable1.addCell(cell); cell = new PdfPCell(new Phrase(SYSCATSPACE)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable1.addCell(cell); cell = new PdfPCell(new Phrase(totalspac)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable1.addCell(cell); cell = new PdfPCell(new Phrase(usablespac)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable1.addCell(cell); cell = new PdfPCell(new Phrase(usableper)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); // cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // aTable1.addCell(cell); } } } if (impReport.getChart() != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ChartUtilities.writeChartAsPNG(baos, impReport.getChart().getChart(), impReport.getChart().getWidth(), impReport.getChart().getHeight()); } catch (IOException ioe) { } Image img1 = Image.getInstance(baos.toByteArray()); img1.setAbsolutePosition(0, 0); img1.setAlignment(Image.MIDDLE);// document.add(img1); } document.add(aTable1); document.close(); } catch (Exception e) { // TODO: handle exception } }