List of usage examples for java.util Hashtable clear
public synchronized void clear()
From source file:com.instantme.api.InstagramAPI.java
public boolean login(String user, String password, IAnimation anim) { IHTTPResponseHandler step1 = new IHTTPResponseHandler() { public boolean Response30X(HttpConnection connection, Hashtable cookies) { return false; }//from www .j a va 2 s .c om public boolean Response20X(HttpConnection connection, Hashtable cookies) { return cookies.get("csrftoken") != null; } public boolean ResponseOthers(HttpConnection connection, Hashtable cookies) { return false; } }; IHTTPResponseHandler step2 = new IHTTPResponseHandler() { public boolean Response30X(HttpConnection connection, Hashtable cookies) { if (cookies.get("sessionid") == null) { return false; } else { parseUserID(); return true; } } public boolean Response20X(HttpConnection connection, Hashtable cookies) { return false; } public boolean ResponseOthers(HttpConnection connection, Hashtable cookies) { return false; } }; IHTTPResponseHandler step3 = new IHTTPResponseHandler() { public boolean Response30X(HttpConnection connection, Hashtable cookies) { return cookies.get("accessToken") != null; } public boolean Response20X(HttpConnection connection, Hashtable cookies) { return true; } public boolean ResponseOthers(HttpConnection connection, Hashtable cookies) { return false; } }; IHTTPResponseHandler step4 = new IHTTPResponseHandler() { public boolean Response30X(HttpConnection connection, Hashtable cookies) { return cookies.get("accessToken") != null; } public boolean Response20X(HttpConnection connection, Hashtable cookies) { return false; } public boolean ResponseOthers(HttpConnection connection, Hashtable cookies) { return false; } }; this.user = user; this.password = password; // clear all cookies and session information cookies.clear(); lastUrl = ""; logged = false; Hashtable getParams = new Hashtable(); getParams.put("client_id", CLIENT_ID); getParams.put("redirect_uri", REDIRECT_URI); getParams.put("response_type", "token"); getParams.put("scope", "basic+likes+comments+relationships"); println("Step 1"); setAnimation(anim); updateProgress(Locale.getInst().getStr(Locale.LOGIN_1_4)); logged = HttpLoginRequest(HttpConnection.GET, LOGIN_URL, getParams, null, step1); if (logged == false) { println("Failed at step 1"); return false; } Hashtable postParams = new Hashtable(); postParams.put("csrfmiddlewaretoken", cookies.get("csrftoken")); postParams.put("username", user); postParams.put("password", password); postParams.put("scope", "basic+likes+comments+relationships"); println("Step 2"); updateProgress(Locale.getInst().getStr(Locale.LOGIN_2_4)); logged = HttpLoginRequest(HttpConnection.POST, LOGIN_URL, getParams, postParams, step2); if (logged == false) { println("Failed at step 2"); return logged; } println("Step 3"); updateProgress(Locale.getInst().getStr(Locale.LOGIN_3_4)); logged = HttpLoginRequest(HttpConnection.GET, AUTH_URL, getParams, null, step3); if (logged == false) { println("Failed at step 3"); return logged; } step1 = step2 = step3 = null; updateProgress(Locale.getInst().getStr(Locale.LOGIN_4_4)); if (cookies.get("accessToken") == null) { postParams.clear(); postParams.put("csrfmiddlewaretoken", cookies.get("csrftoken")); postParams.put("allow", "Authorize"); postParams.put("scope", "basic+likes+comments+relationships"); println("Step 4"); logged = HttpLoginRequest(HttpConnection.POST, AUTH_URL, getParams, postParams, step4); if (logged == false) { println("Failed at step 4"); return logged; } } step4 = null; // update user info getFullUserInfo(userInfo, getAuthUserID(), anim); return logged; }
From source file:com.fiorano.openesb.application.aps.OutPortInst.java
protected void populate(FioranoStaxParser parser) throws XMLStreamException, FioranoException { if (parser.markCursor(APSConstants.OUTPORT_INST)) { // Get Attributes if needs to accessed later. This MUST be done before accessing any data of element. Hashtable attributes = parser.getAttributes(); m_bIsSyncRequestType = XMLUtils//w w w . jav a2 s.com .getStringAsBoolean((String) attributes.get(APSConstants.IS_SYNC_REQUEST_TYPE));//XMLDmiUtil.getAttributeAsBoolean(port, "isSyncRequestType"); m_bisDisabled = XMLUtils.getStringAsBoolean((String) attributes.get(APSConstants.IS_DISABLED));//XMLDmiUtil.getAttributeAsBoolean(port, "isSyncRequestType"); while (parser.nextElement()) { String nodeName = parser.getLocalName(); if (nodeName.equalsIgnoreCase("Name")) { m_strPortName = parser.getText();//XMLUtils.getNodeValueAsString(child).toUpperCase(); } else if (nodeName.equalsIgnoreCase("Description")) { m_strDscription = parser.getText();//XMLUtils.getNodeValueAsString(child); } else if (nodeName.equalsIgnoreCase("StandardXSD")) { if ("ON_EXCEPTION".equals(m_strPortName)) m_strXSD = CommonSchemas.ERROR_XSD; } else if (nodeName.equalsIgnoreCase(PortInstConstants.PORT_XSD)) { m_strXSD = parser.getCData();//XMLUtils.getNodeValueAsString(child); } else if (nodeName.equalsIgnoreCase(PortInstConstants.PORT_XSDREF)) { m_strXSDRef = parser.getText();//XMLUtils.getNodeValueAsString(child); } else if (nodeName.equalsIgnoreCase("SetContextXSL")) { m_strContextXSL = parser.getCData();//XMLUtils.getNodeValueAsString(child); } else if (nodeName.equalsIgnoreCase("SetContextInfo")) { m_strContextInfo = parser.getCData();//XMLUtils.getNodeValueAsString(child); } else if (nodeName.equalsIgnoreCase("SetTransformationType")) { m_transformerType = parser.getText();//XMLUtils.getNodeValueAsString(child); } else if (nodeName.equalsIgnoreCase("JavaClass")) { m_strJavaClass = parser.getText();//XMLUtils.getNodeValueAsString(child); } else if (nodeName.equalsIgnoreCase("Param")) { Param paramDmi = new Param(); paramDmi.setFieldValues(parser); addParam(paramDmi); } } if (attributes != null) { attributes.clear(); attributes = null; } } validate(); }
From source file:edu.ku.brc.specify.web.SpecifyExplorer.java
/** * @param dataObj//from ww w.j a va 2s. c o m * @param labelHashMap */ protected void fillLabelMap(final FormDataObjIFace dataObj, final Hashtable<String, String> labelHashMap) { labelHashMap.clear(); if (dataObj instanceof Treeable<?, ?, ?>) { Treeable<?, ?, ?> node = (Treeable<?, ?, ?>) dataObj; TreeDefItemIface<?, ?, ?> def = node.getDefinitionItem(); //String defName = def.getName(); Treeable<?, ?, ?> parentNode = node.getParent(); if (parentNode != null) { TreeDefItemIface<?, ?, ?> parentDef = parentNode.getDefinitionItem(); if (parentDef != null) { String parentDefName = parentDef.getName(); labelHashMap.put("parent", parentDefName); } } TreeDefItemIface<?, ?, ?> childDef = def.getChild(); if (childDef != null) { String childDefName = childDef.getName(); labelHashMap.put("children", childDefName); } if (dataObj.getClass() == Taxon.class) { labelHashMap.put("definitionItem", "Taxonomy"); } } }
From source file:org.treasurehunter.bcaching.ImportBcachingTask.java
protected void doInBackground(Handler handler) { try {/*from ww w . j av a 2s . com*/ Log.d("TreasureHunter", "Doing bcaching login"); mComm.validateCredentials(); } catch (Exception ex) { Log.e("TreasureHunter", "Bcaching.com login failed", ex); mProcessStatus.abortedBeforeStart(); if (!isAborted()) mErrorDisplayer.displayError(R.string.bcaching_login_failed); return; } if (isAborted()) { mProcessStatus.abortedBeforeStart(); return; } Hashtable<String, String> params = new Hashtable<String, String>(); params.put("a", "find"); if (mUsesCenterCoord) { params.put("lat", String.valueOf(mCenterLat)); params.put("lon", String.valueOf(mCenterLon)); } else { // bbox=lat1,lon1,lat2,lon2 params.put("bbox", String.valueOf(mLatLow) + "," + String.valueOf(mLonLow) + "," + String.valueOf(mLatHigh) + "," + String.valueOf(mLonHigh)); params.put("lon", String.valueOf(mCenterLon)); } params.put("wpts", "0"); params.put("maxcount", Integer.toString(mMaxCount)); params.put("fmt", "json"); params.put("timeAsLong", "1"); // Don't return "new Date(xxxx)" params.put("idsonly", "1"); // Don't get name or other additional // properties if (mBcachingConfig.shouldDownloadMyFinds()) { params.put("found", "b"); } else { params.put("found", "0"); } if (mBcachingConfig.shouldDownloadMyHides()) { params.put("own", "b"); } else { params.put("own", "0"); } params.put("app", "TreasureHunter"); String response; try { Log.d("TreasureHunter", "Sending query"); response = readResponse(mComm.SendRequest(params)); } catch (Exception ex) { Log.e("TreasureHunter", "SendRequest failed", ex); mProcessStatus.abortedBeforeStart(); if (!isAborted()) mErrorDisplayer.displayError(R.string.bcaching_sendrequest_failed); return; } if (isAborted()) { mProcessStatus.abortedBeforeStart(); return; } StringBuilder csvIds = new StringBuilder(); int detailsCount = 0; try { JSONObject obj = new JSONObject(response); JSONArray summary = obj.getJSONArray("data"); int count = summary.length(); Log.v("TreasureHunter", "Number of caches: " + count); mProcessStatusListener.onProcessNewMaxProgress(count); if (count == 0) { mProcessStatus.abortedBeforeStart(); if (!isAborted()) mErrorDisplayer.displayError(R.string.bcaching_no_nearby_caches); return; } if (isAborted()) { mProcessStatus.abortedBeforeStart(); return; } for (int i = 0; i < count; i++) { JSONObject cacheObject = summary.getJSONObject(i); String cacheId = cacheObject.getString("wpt"); long localLastMod = mDbFrontend.getLastUpdatedTime(cacheId); long serverLastMod = 1; if (localLastMod != 0) { // String serverLastModStr = // cacheObject.getString("lastMod"); // serverLastMod = // Long.parseLong(serverLastModStr.replace("new Date(", // "").replace(")", "")); serverLastMod = cacheObject.getLong("lastMod"); } if (serverLastMod >= localLastMod) { detailsCount += 1; if (csvIds.length() > 0) { csvIds.append(','); } int id = cacheObject.getInt("id"); csvIds.append(String.valueOf(id)); } } } catch (Exception ex) { Log.e("TreasureHunter", "Processing SendRequest result failed", ex); mProcessStatus.abortedBeforeStart(); if (!isAborted()) mErrorDisplayer.displayError(R.string.bcaching_processing_result_failed); return; } mProcessStatus.setMaxProgress(detailsCount); params.clear(); params.put("a", "detail"); params.put("desc", "html"); params.put("ids", csvIds.toString()); params.put("tbs", "1"); params.put("wpts", "1"); params.put("logs", "20"); params.put("fmt", "gpx"); params.put("app", "TreasureHunter"); if (isAborted()) { mProcessStatus.abortedBeforeStart(); return; } InputStream is; try { Log.d("TreasureHunter", "Downloading cache details"); is = mComm.SendRequest(params); } catch (Exception ex) { Log.e("TreasureHunter", "Detail Request failed", ex); mProcessStatus.abortedBeforeStart(); if (!isAborted()) mErrorDisplayer.displayError(R.string.bcaching_detail_request_failed); return; } if (isAborted()) { mProcessStatus.abortedBeforeStart(); return; } InputStreamReader isr = new InputStreamReader(is); mProcessStatus.willStartLoading(); boolean success = false; try { XmlFiniteStateMachine.importFromReader(Source.BCACHING, isr, mProcessStatus, this, mUsername); success = true; // No assertion thrown } catch (XmlPullParserException e) { if (!isAborted()) mErrorDisplayer.displayError(R.string.error_parsing_file, e.getMessage()); } catch (IOException e) { if (!isAborted()) mErrorDisplayer.displayError(R.string.error_reading_file, e.getMessage()); } mProcessStatus.stoppedAllLoading(success); }
From source file:edu.ku.brc.specify.web.SpecifyExplorer.java
/** * @param dataObj/* w w w. j a v a2 s .co m*/ */ protected void processDataList(final PrintWriter out, final List<?> list, final String sql) { if (StringUtils.isEmpty(template)) { out.println("The template file is empty!"); } FormDataObjIFace dataObj = (FormDataObjIFace) list.get(0); String linkField = ""; ClassDisplayInfo cdi = classHash.get(dataObj.getClass().getSimpleName()); if (cdi != null) { linkField = cdi.getLinkField(); } int contentInx = template.indexOf(contentTag); String subContent = template.substring(0, contentInx); out.println(StringUtils.replace(subContent, "<!-- Title -->", dataObj.getIdentityTitle())); //fillLabelMap(dataObj, labelMap); Hashtable<Integer, String> ordered = new Hashtable<Integer, String>(); Vector<String> unOrdered = new Vector<String>(); Hashtable<String, Boolean> hasData = new Hashtable<String, Boolean>(); out.println("<table border=\"0\" width=\"100%\"<tr><td nowrap=\"nowrap\">select * " + StringUtils.replace(sql, packageName, "") + "</td></tr>"); out.println("<tr><td nowrap=\"nowrap\">Records Returned: " + list.size() + "</td></tr></table><br/>"); out.println("<table width=\"100%\" cellspacing=\"0\" class=\"brdr\">\n"); try { for (Object dobj : list) { dataObj = (FormDataObjIFace) dobj; for (Field field : dataObj.getClass().getDeclaredFields()) { String fieldName = field.getName(); FieldDisplayInfo fdi = cdi.getField(fieldName); if (fdi != null && (fdi.isSkipped() || !fdi.isForDisplay())) { continue; } String fldNameLower = fieldName.toLowerCase(); if (fldNameLower.startsWith(dataObj.getClass().getSimpleName().toLowerCase()) && fldNameLower.endsWith("id")) { continue; } try { Object data = getData(field, dataObj); if (data != null && !(data instanceof Set<?>)) { hasData.put(fieldName, true); } } catch (Exception ex) { ex.printStackTrace(); } } } out.println("<tr><th class=\"brdr\">Row</th>"); for (Field field : dataObj.getClass().getDeclaredFields()) { String fieldName = field.getName(); if (hasData.get(fieldName) == null) { continue; } FieldDisplayInfo fdi = cdi.getField(fieldName); // should never be null String labelStr = labelMap.get(fieldName); if (StringUtils.isEmpty(labelStr)) { labelStr = UIHelper.makeNamePretty(fieldName); } String row = "<th class=\"brdr\">" + labelStr + "</th>"; Integer inx = fdi != null ? fdi.getOrder() : null; if (inx == null) { unOrdered.add(row); } else { ordered.put(inx, row); } } fillRows(out, ordered, unOrdered); out.println("</tr>"); int cnt = 1; for (Object dobj : list) { ordered.clear(); unOrdered.clear(); out.println("<tr><th class=\"brdr\" align=\"center\">" + cnt + "</th>"); dataObj = (FormDataObjIFace) dobj; for (Field field : dataObj.getClass().getDeclaredFields()) { String fieldName = field.getName(); if (hasData.get(fieldName) == null) { continue; } FieldDisplayInfo fdi = cdi.getField(fieldName); String row = null; try { Object data = getData(field, dataObj); if (data != null && !(data instanceof Set<?>)) { String val; if (fieldName.equals(linkField)) { val = formatFDI(dataObj, formatValue(data)); } else { val = formatValue(data); } row = "<td align=\"center\" class=\"brdr" + ((cnt % 2 == 0) ? "even" : "odd") + "\">" + (StringUtils.isNotEmpty(val) ? val : " ") + "</td>"; } else { row = "<td align=\"center\" class=\"brdr" + ((cnt % 2 == 0) ? "even" : "odd") + "\"> </td>"; } } catch (Exception ex) { ex.printStackTrace(); } if (row != null) { Integer inx = fdi != null ? fdi.getOrder() : null; if (inx == null) { unOrdered.add(row); } else { ordered.put(inx, row); } } } fillRows(out, ordered, unOrdered); out.println("</tr>\n"); cnt++; } out.println("</table>\n"); // This should be externalized if (dataObj.getClass() == Locality.class || dataObj.getClass() == CollectingEvent.class || dataObj.getClass() == CollectionObject.class || dataObj.getClass() == Taxon.class || dataObj.getClass() == Accession.class) { createMapLink(out, list, dataObj.getClass()); } out.println(template.substring(contentInx + contentTag.length() + 1, template.length())); } catch (Exception ex) { ex.printStackTrace(); System.out.println(ex.toString()); out.println("Sorry"); } }
From source file:org.sakaiproject.dav.DavServlet.java
/** * Copy or name a resource or collection. * //from ww w.j a v a2s. co m * @param resources * Resources implementation to be used * @param errorList * Hashtable containing the list of errors which occurred during the copy operation * @param source * Path of the resource to be copied * @param dest * Destination path */ private boolean copyResource(DirContextSAKAI resources, Hashtable<String, Integer> errorList, String source, String dest, boolean move) { if (M_log.isDebugEnabled()) M_log.debug("Copy: " + source + " To: " + dest); source = fixDirPathSAKAI(source); dest = fixDirPathSAKAI(dest); if (prohibited(source) || prohibited(dest)) { errorList.put(source, new Integer(SakaidavStatus.SC_FORBIDDEN)); return false; } source = adjustId(source); dest = adjustId(dest); // Copy try { boolean isCollection = contentHostingService.getProperties(source) .getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION); /* https://jira.sakaiproject.org/browse/SAK-23639 if (move) { contentHostingService.rename(source, dest); } else */ // NOTE: moves cause a copy as below and a delete around line 2960, if rename() is fixed the remove that code also if (isCollection) { copyCollection(source, dest); } else { contentHostingService.copy(source, dest); } } catch (EntityPropertyNotDefinedException e) { // System.out.println("propnotdef " + e); errorList.put(source, new Integer(SakaidavStatus.SC_INTERNAL_SERVER_ERROR)); return false; } catch (EntityPropertyTypeException e) { // System.out.println("propntype " + e); errorList.put(source, new Integer(SakaidavStatus.SC_INTERNAL_SERVER_ERROR)); return false; } catch (IdUsedException e) // internal error because caller checked for this { // System.out.println("idunused " + e); errorList.put(source, new Integer(SakaidavStatus.SC_INTERNAL_SERVER_ERROR)); return false; } catch (IdUniquenessException e) { // System.out.println("iduniqu " + e); errorList.put(source, new Integer(SakaidavStatus.SC_INTERNAL_SERVER_ERROR)); return false; } catch (IdLengthException e) { // System.out.println("idlen " + e); errorList.put(source, new Integer(SakaidavStatus.SC_FORBIDDEN)); return false; } catch (InconsistentException e) { // System.out.println("inconsis " + e); errorList.put(source, new Integer(SakaidavStatus.SC_CONFLICT)); return false; } catch (PermissionException e) { // System.out.println("perm " + e); errorList.put(source, new Integer(SakaidavStatus.SC_FORBIDDEN)); return false; } catch (InUseException e) { // System.out.println("in use " + e); errorList.put(source, new Integer(SakaidavStatus.SC_CONFLICT)); return false; } catch (IdUnusedException e) { // System.out.println("unused " + e); errorList.put(source, new Integer(SakaidavStatus.SC_NOT_FOUND)); return false; } catch (OverQuotaException e) { // System.out.println("quota " + e); errorList.put(source, new Integer(SakaidavStatus.SC_FORBIDDEN)); return false; } catch (IdInvalidException e) { // System.out.println("quota " + e); errorList.put(source, new Integer(SakaidavStatus.SC_FORBIDDEN)); return false; } catch (TypeException e) { // System.out.println("type " + e); errorList.put(source, new Integer(SakaidavStatus.SC_FORBIDDEN)); return false; } catch (ServerOverloadException e) { // System.out.println("overload " + e); errorList.put(source, new Integer(SakaidavStatus.SC_INTERNAL_SERVER_ERROR)); return false; } // We did not have an error errorList.clear(); return true; }
From source file:edu.ku.brc.specify.utilapps.BuildSampleDatabase.java
/** * @param treeDef// ww w .ja va2 s. c o m * @return */ public LithoStrat convertLithoStratFromCSV(final LithoStratTreeDef treeDef) { Hashtable<String, LithoStrat> lithoStratHash = new Hashtable<String, LithoStrat>(); lithoStratHash.clear(); File file = new File("demo_files/Stratigraphy.csv"); if (!file.exists()) { log.error("Couldn't file[" + file.getAbsolutePath() + "] checking the config dir"); file = XMLHelper.getConfigDir("Stratigraphy.csv"); if (!file.exists()) { file = new File("Specify/demo_files/Stratigraphy.csv"); } } if (file == null || !file.exists()) { log.error("Couldn't file[" + file.getAbsolutePath() + "]"); return null; } List<String> lines = null; try { lines = FileUtils.readLines(file); } catch (Exception ex) { ex.printStackTrace(); return null; } startTx(); // setup the root Geography record (planet Earth) LithoStrat earth = new LithoStrat(); earth.initialize(); earth.setName(getResourceString("Earth")); earth.setFullName(earth.getName()); earth.setNodeNumber(1); earth.setHighestChildNodeNumber(1); earth.setRankId(0); earth.setDefinition(treeDef); LithoStratTreeDefItem defItem = treeDef.getDefItemByRank(0); earth.setDefinitionItem(defItem); persist(earth); frame.setDesc("Adding Stratigraphy Objects"); frame.setProcess(0, lines.size()); int counter = 0; // for each old record, convert the record for (String line : lines) { if (counter == 0) { counter = 1; continue; // skip header line } if (counter % 100 == 0) { frame.setProcess(counter); log.info("Converted " + counter + " Stratigraphy records"); } String[] columns = StringUtils.splitPreserveAllTokens(line, ','); if (columns.length < 7) { log.error("Skipping[" + line + "]"); continue; } // grab the important data fields from the old record String superGroup = columns[2]; String lithoGroup = columns[3]; String formation = columns[4]; String member = columns[5]; String bed = columns[6]; // create a new Litho Stratigraphy object from the old data @SuppressWarnings("unused") LithoStrat newStrat = convertOldStratRecord(superGroup, lithoGroup, formation, member, bed, earth); counter++; } frame.setProcess(counter); log.info("Converted " + counter + " Stratigraphy records"); TreeHelper.fixFullnameForNodeAndDescendants(earth); earth.setNodeNumber(1); fixNodeNumbersFromRoot(earth); commitTx(); /*startTx(); TreeHelper.fixFullnameForNodeAndDescendants(earth); earth.setNodeNumber(1); fixNodeNumbersFromRoot(earth); printTree(earth, 0); saveTree(earth); commitTx();*/ log.info("Converted " + counter + " Stratigraphy records"); // set up Geography foreign key mapping for locality lithoStratHash.clear(); return earth; }
From source file:edu.ku.brc.specify.utilapps.BuildSampleDatabase.java
/** * @param treeDef//from w w w.j a va2 s . c o m * @return */ public Geography convertGeographyFromXLS(final GeographyTreeDef treeDef) { frame.setDesc("Building Geography Tree..."); Hashtable<String, Geography> geoHash = new Hashtable<String, Geography>(); geoHash.clear(); String fileName = "Geography.xls"; File file = XMLHelper.getConfigDir("../demo_files/" + fileName); if (!file.exists()) { log.error("Couldn't file[" + file.getAbsolutePath() + "] checking the config dir"); file = XMLHelper.getConfigDir(fileName); if (!file.exists()) { file = new File("Specify/demo_files/" + fileName); } } if (file == null || !file.exists()) { log.error("Couldn't file[" + file.getAbsolutePath() + "]"); return null; } // setup the root Geography record (planet Earth) Geography earth = new Geography(); earth.initialize(); earth.setName(getResourceString("Earth")); earth.setFullName(earth.getName()); earth.setNodeNumber(1); earth.setHighestChildNodeNumber(1); earth.setRankId(0); earth.setDefinition(treeDef); GeographyTreeDefItem defItem = treeDef.getDefItemByRank(0); earth.setDefinitionItem(defItem); int counter = 0; try { startTx(); persist(earth); String[] cells = new String[4]; 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); } }); } while (rows.hasNext()) { if (counter == 0) { counter = 1; rows.next(); continue; } if (counter % 100 == 0) { if (frame != null) frame.setProcess(counter); log.info("Converted " + counter + " Geography records"); } HSSFRow row = (HSSFRow) rows.next(); Iterator<?> cellsIter = row.cellIterator(); int i = 0; while (cellsIter.hasNext() && i < 4) { HSSFCell cell = (HSSFCell) cellsIter.next(); if (cell != null) { cells[i] = StringUtils.trim(cell.getRichStringCellValue().getString()); i++; } } // Sets nulls to unused cells for (int j = i; j < 4; j++) { cells[j] = null; } //System.out.println(); @SuppressWarnings("unused") Geography newGeo = convertGeographyRecord(cells[0], cells[1], cells[2], cells[3], earth); counter++; } } catch (Exception ex) { ex.printStackTrace(); } if (frame != null) frame.setProcess(counter); log.info("Converted " + counter + " Geography records"); frame.setDesc("Saving Geography Tree..."); frame.getProcessProgress().setIndeterminate(true); TreeHelper.fixFullnameForNodeAndDescendants(earth); earth.setNodeNumber(1); fixNodeNumbersFromRoot(earth); commitTx(); /*startTx(); TreeHelper.fixFullnameForNodeAndDescendants(earth); earth.setNodeNumber(1); fixNodeNumbersFromRoot(earth); printTree(earth, 0); saveTree(earth); commitTx();*/ log.info("Converted " + counter + " Stratigraphy records"); // set up Geography foreign key mapping for locality geoHash.clear(); return earth; }
From source file:edu.ku.brc.specify.utilapps.BuildSampleDatabase.java
/** * @param treeDef// ww w . ja va 2 s. c o m * @return */ public GeologicTimePeriod convertChronoStratFromXLS(final GeologicTimePeriodTreeDef treeDef, final Agent userAgent) { startTx(); GeologicTimePeriodTreeDefItem root = createGeologicTimePeriodTreeDefItem(null, treeDef, "Root", 0); GeologicTimePeriodTreeDefItem era = createGeologicTimePeriodTreeDefItem(root, treeDef, "Erathem/Era", 100); GeologicTimePeriodTreeDefItem period = createGeologicTimePeriodTreeDefItem(era, treeDef, "System/Period", 200); GeologicTimePeriodTreeDefItem series = createGeologicTimePeriodTreeDefItem(period, treeDef, "Series/Epoch", 300); @SuppressWarnings("unused") GeologicTimePeriodTreeDefItem member = createGeologicTimePeriodTreeDefItem(series, treeDef, "Stage/Age", 400); persist(root); commitTx(); series.setIsInFullName(true); frame.setDesc("Building ChronoStratigraphy Tree..."); Hashtable<String, GeologicTimePeriod> chronoHash = new Hashtable<String, GeologicTimePeriod>(); chronoHash.clear(); String fileName = "chronostrat_tree.xls"; File file = XMLHelper.getConfigDir("../demo_files/" + fileName); if (!file.exists()) { log.error("Couldn't file[" + file.getAbsolutePath() + "] checking the config dir"); file = XMLHelper.getConfigDir(fileName); if (!file.exists()) { file = new File("Specify/demo_files/" + fileName); } } if (file == null || !file.exists()) { log.error("Couldn't file[" + file.getAbsolutePath() + "]"); return null; } // setup the root ChronoStrat record (planet Earth) GeologicTimePeriod rootNode = new GeologicTimePeriod(); rootNode.initialize(); rootNode.setName(getResourceString("Root")); rootNode.setFullName(rootNode.getName()); rootNode.setRankId(0); rootNode.setDefinition(treeDef); rootNode.setDefinitionItem(root); rootNode.setCreatedByAgent(userAgent); int counter = 0; try { startTx(); persist(rootNode); String[] cells = new String[4]; 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); } }); } while (rows.hasNext()) { if (counter == 0) { counter = 1; continue; } if (counter % 100 == 0) { if (frame != null) frame.setProcess(counter); log.info("Converted " + counter + " ChronoStrat records"); } HSSFRow row = (HSSFRow) rows.next(); Iterator<?> cellsIter = row.cellIterator(); int i = 0; while (cellsIter.hasNext() && i < 4) { HSSFCell cell = (HSSFCell) cellsIter.next(); if (cell != null) { cells[i] = StringUtils.trim(cell.getRichStringCellValue().getString()); i++; } } for (int j = i; j < 4; j++) { cells[j] = null; } //System.out.println(); @SuppressWarnings("unused") GeologicTimePeriod newGeo = convertChronoStratRecord(cells[0], cells[1], cells[2], cells[3], rootNode, userAgent); counter++; } input.close(); } catch (Exception ex) { ex.printStackTrace(); } if (frame != null) frame.setProcess(counter); log.info("Converted " + counter + " ChronoStrat records"); TreeHelper.fixFullnameForNodeAndDescendants(rootNode); rootNode.setNodeNumber(1); fixNodeNumbersFromRoot(rootNode); commitTx(); log.info("Converted " + counter + " Stratigraphy records"); // set up ChronoStrat foreign key mapping for locality chronoHash.clear(); return rootNode; }
From source file:edu.ku.brc.specify.utilapps.BuildSampleDatabase.java
/** * @param treeDef/*from ww w. j a va 2 s .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; }