List of usage examples for java.util Vector get
public synchronized E get(int index)
From source file:imapi.OnlineDatabaseActions.java
long getDatabaseInstancesCount(StringObject queryPrefixesObj, StringObject countAllInstancesQueryObj) { long returnResult = 0; String query = queryPrefixesObj.getString() + "\n" + countAllInstancesQueryObj.getString(); InputStream answerStream = performDatabaseQuery(query); if (answerStream == null) { return ApiConstants.IMAPIFailCode; }//from w w w. j av a 2 s .co m Vector<String> tempVec = new Vector<String>(); int ret = this.readJsonUriVals(answerStream, tempVec); if (ret != ApiConstants.IMAPISuccessCode) { return ret; } if (tempVec.size() == 1 && tempVec.get(0).length() > 0) { returnResult = Long.parseLong(tempVec.get(0)); } return returnResult; }
From source file:edu.ku.brc.specify.tasks.ReportsBaseTask.java
/** * @param cmdAction/* w w w . j av a 2s. c o m*/ */ protected void runReport(final CommandAction cmdAction) { NavBoxItemIFace toRun = null; SpReport spRepToRun = null; CommandAction runAction = null; CommandAction repAction = null; RecordSetIFace rs = null; if (cmdAction.isAction(RUN_REPORT)) //RunReport was clicked or dropped on { runAction = cmdAction; Object data = cmdAction.getData(); if (data instanceof CommandAction && ((CommandAction) data).isAction(PRINT_REPORT)) { repAction = (CommandAction) data; } } else if (cmdAction.isAction(PRINT_REPORT))//Report was dropped upon { repAction = cmdAction; Object data = cmdAction.getData(); if (data instanceof CommandAction && ((CommandAction) data).isAction(RUN_REPORT)) { runAction = (CommandAction) data; } else if (data instanceof RecordSetIFace) { rs = (RecordSetIFace) data; } } if (runAction != null && repAction == null) { toRun = selectReport("ReportRunReport"); //XXX add help if (toRun != null) { CommandAction cmd = (CommandAction) toRun.getData(); if (cmd.getProperty("spreport") != null) { RecordSet repRS = (RecordSet) cmd.getProperty("spreport"); spRepToRun = loadReport(repRS); } } } else if ((runAction != null || rs != null) && repAction != null) { spRepToRun = loadReport((RecordSet) repAction.getProperty("spreport")); } if (spRepToRun != null) { if (spRepToRun.getReportObject() instanceof WorkbenchTemplate) { //get workbench WorkbenchTemplate repTemplate = (WorkbenchTemplate) spRepToRun.getReportObject(); DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); try { List<Workbench> wbs = session.getDataList(Workbench.class, "specifyUser", AppContextMgr.getInstance().getClassObject(SpecifyUser.class), DataProviderSessionIFace.CompareType.Equals); Vector<Workbench> choices = new Vector<Workbench>(); for (Workbench wb : wbs) { if (repTemplate.containsAllMappings(wb.getWorkbenchTemplate())) { choices.add(wb); } } if (choices.size() == 0) { UIRegistry.displayInfoMsgDlgLocalized("ReportsBaseTask.NO_WBS_FOR_REPORT", spRepToRun.getName()); return; } Workbench repWB = null; if (choices.size() == 1) { repWB = choices.get(0); } else { ChooseFromListDlg<Workbench> wbDlg = new ChooseFromListDlg<Workbench>( (Frame) UIRegistry.getTopWindow(), getResourceString("ReportsBaseTesk.SELECT_WB"), choices, IconManager.getIcon(name, IconManager.IconSize.Std24)); UIHelper.centerAndShow(wbDlg); repWB = wbDlg.getSelectedObject(); if (wbDlg.isCancelled() || repWB == null) { return; } } RecordSet wbRS = new RecordSet(); wbRS.initialize(); wbRS.set(repWB.getName(), Workbench.getClassTableId(), RecordSet.GLOBAL); wbRS.addItem(repWB.getId()); rs = wbRS; } finally { session.close(); } } QueryBldrPane.runReport(spRepToRun, spRepToRun.getName(), rs); } else if (toRun != null) { CommandDispatcher.dispatch((CommandAction) toRun.getData()); } }
From source file:hu.sztaki.lpds.pgportal.portlets.workflow.EasyWorkflowPortlet.java
/** * Save enduser parameters// w w w .j av a 2 s. co m */ public void doSaveEWorkflowParams(ActionRequest request, ActionResponse response) throws PortletException { try { String workflow = request.getParameter("workflow"); //findinWF = new Hashtable(); // Vector eparam = getEConfParam(request.getRemoteUser(), workflow);//easy parameterek // PortalCacheService.getInstance().getUser(request.getRemoteUser()).getConfiguringEParams(); //findinWF = new Hashtable(); // System.out.println("NEW EASY PARAMS: "); Hashtable wfhash = new Hashtable(); for (int i = 0; i < PortalCacheService.getInstance().getUser(request.getRemoteUser()) .getConfiguringEParams().size(); i++) { String nv = " "; if (request.getParameter("eparam_" + i) != null) { nv = request.getParameter("eparam_" + i).replace('\\', '/'); } ((Hashtable) PortalCacheService.getInstance().getUser(request.getRemoteUser()) .getConfiguringEParams().get(i)).put("newvalue", nv); // System.out.println("param: " + i + " [" + PortalCacheService.getInstance().getUser(request.getRemoteUser()).getConfiguringEParams().get(i) + "]"); if (wfhash.get(((Hashtable) PortalCacheService.getInstance().getUser(request.getRemoteUser()) .getConfiguringEParams().get(i)).get("wfID")) == null) {//meg nincs ilyen wfID Hashtable wfh = new Hashtable(); wfh.put("" + i, (Hashtable) PortalCacheService.getInstance().getUser(request.getRemoteUser()) .getConfiguringEParams().get(i)); wfhash.put(((Hashtable) PortalCacheService.getInstance().getUser(request.getRemoteUser()) .getConfiguringEParams().get(i)).get("wfID"), wfh); } else { ((Hashtable) wfhash.get(((Hashtable) PortalCacheService.getInstance() .getUser(request.getRemoteUser()).getConfiguringEParams().get(i)).get("wfID"))) .put("" + i, (Hashtable) PortalCacheService.getInstance() .getUser(request.getRemoteUser()).getConfiguringEParams().get(i)); } } // System.out.println("WFre bobntott hasban(wf) hasbn(params i) hash(values) PARAMS: " + wfhash); Enumeration keys = wfhash.keys(); while (keys.hasMoreElements()) {//WF-ek bejarasa String wfID = (String) keys.nextElement(); Hashtable hsh = new Hashtable(); hsh.put("url", PortalCacheService.getInstance().getUser(request.getRemoteUser()).getWorkflow(wfID) .getWfsID()); ServiceType st = InformationBase.getI().getService("wfs", "portal", hsh, new Vector()); PortalWfsClient pc = (PortalWfsClient) Class.forName(st.getClientObject()).newInstance(); pc.setServiceURL(st.getServiceUrl()); pc.setServiceID(st.getServiceID()); ComDataBean tmp = new ComDataBean(); tmp.setPortalID(PropertyLoader.getInstance().getProperty("service.url")); tmp.setUserID(request.getRemoteUser()); tmp.setWorkflowID(wfID); Vector wfconfigdt = pc.getWorkflowConfigData(tmp); // System.out.println("WF letoltve:" + wfID); Enumeration keysp = ((Hashtable) wfhash.get(wfID)).keys(); while (keysp.hasMoreElements()) {//EParameterek bejarasa String eparamID = (String) keysp.nextElement(); Hashtable ep = (Hashtable) ((Hashtable) wfhash.get(wfID)).get(eparamID); // System.out.println(" Eparam:" + eparamID + " values ep[" + ep + "]"); for (int i = 0; i < wfconfigdt.size(); i++) { // replace special characters... String jobtxt = new String(((JobPropertyBean) wfconfigdt.get(i)).getTxt()); ((JobPropertyBean) wfconfigdt.get(i)).setTxt(replaceTextS(jobtxt)); if (("" + ((JobPropertyBean) wfconfigdt.get(i)).getId()).equals(ep.get("jobID"))) {//job id // System.out.println(" Eparamjobidfound:" + ep.get("jobID")); if (ep.get("type").equals("iport")) { ((JobPropertyBean) wfconfigdt.get(i)).getInput("" + ep.get("typeID")).getData() .put(ep.get("name"), ep.get("newvalue")); } else if (ep.get("type").equals("oport")) { ((JobPropertyBean) wfconfigdt.get(i)).getOutput("" + ep.get("typeID")).getData() .put(ep.get("name"), ep.get("newvalue")); } else {//exe ((JobPropertyBean) wfconfigdt.get(i)).addExe((String) ep.get("name"), (String) ep.get("newvalue")); } i = wfconfigdt.size();//kilep } } } //save pc.setWorkflowConfigData(tmp, wfconfigdt); System.out.println("EWF saved:" + wfID); } //do not delete EINSTANCE // WorkflowData wData = PortalCacheService.getInstance().getUser(request.getRemoteUser()).getWorkflow(workflow); // if (wData.getEinstanceID() != null) { //// System.out.println("EINSTANCE exists, delete... :" + wData.getEinstanceID()); // RealWorkflowUtils.getInstance().deleteWorkflowInstance(request.getRemoteUser(), workflow, "" + wData.getEinstanceID()); // } // // send configure ID to storage begin // boolean retUploadFiles = true; try { String storageID = PortalCacheService.getInstance().getUser(request.getRemoteUser()) .getWorkflow(workflow).getStorageID(); String confID = request.getParameter("confIDparam"); // System.out.println("confID request getParameter : " + confID); // Hashtable hshsto = new Hashtable(); hshsto.put("url", storageID); ServiceType sts = InformationBase.getI().getService("storage", "portal", hshsto, new Vector()); // PortalStorageClient ps = (PortalStorageClient) Class.forName(sts.getClientObject()).newInstance(); ps.setServiceURL(storageID); ps.setServiceID(sts.getServiceID()); UploadWorkflowBean uwb = new UploadWorkflowBean(); uwb.setConfID(confID); retUploadFiles = ps.uploadWorkflowFiles(uwb); if (!retUploadFiles) { // res.put("msg", "workflow.config.files.notuploaded"); } } catch (Exception e) { e.printStackTrace(); } // // send configure ID to storage end // } catch (Exception e) { request.setAttribute("msg", "workflow.easy.saved.error"); e.printStackTrace(); } request.setAttribute("jsp", mainjsp); request.setAttribute("msg", "workflow.easy.saved"); }
From source file:edu.ku.brc.specify.toycode.mexconabio.MexConvToSQL.java
/** * /*from w ww . ja v a 2 s.c o m*/ */ public void convert(final String databaseName, final String tableName, final String srcFileName, final String xmlFileName) { String[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", }; HashMap<String, Integer> monthHash = new HashMap<String, Integer>(); for (String mn : months) { monthHash.put(mn, monthHash.size() + 1); } Connection conn = null; Statement stmt = null; try { conn = DriverManager.getConnection( "jdbc:mysql://localhost/" + databaseName + "?characterEncoding=UTF-8&autoReconnect=true", "root", "root"); stmt = conn.createStatement(); FMPCreateTable fmpInfo = new FMPCreateTable(tableName, null, true); fmpInfo.process(xmlFileName); boolean doCreateTable = true; if (doCreateTable) { processFieldSizes(fmpInfo, srcFileName); PrintWriter pw = new PrintWriter(new File("fields.txt")); int i = 0; for (FieldDef fd : fmpInfo.getFields()) { pw.println(i + " " + fd.getName() + "\t" + fd.getType() + "\t" + fd.isDouble()); i++; } pw.close(); BasicSQLUtils.update(conn, fmpInfo.dropTableStr()); String sqlCreateTable = fmpInfo.createTableStr(); BasicSQLUtils.update(conn, sqlCreateTable); System.out.println(sqlCreateTable); } String prepSQL = fmpInfo.getPrepareStmtStr(true, true); System.out.println(prepSQL); pStmt = conn.prepareStatement(prepSQL); Vector<FieldDef> fieldDefs = fmpInfo.getFields(); int rowCnt = 0; BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(srcFileName))); String str = in.readLine(); str = in.readLine(); while (str != null) { String line = str; char sep = '`'; String sepStr = ""; for (char c : seps) { if (line.indexOf(c) == -1) { sepStr += c; sep = c; break; } } str = StringUtils.replace(str.substring(1, str.length() - 1), "\",\"", sepStr); Vector<String> fields = split(str, sep); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); int col = 1; int inx = 0; for (String fld : fields) { String value = fld.trim(); FieldDef fd = fieldDefs.get(inx); switch (fd.getType()) { case eText: case eMemo: { if (value.length() > 0) { //value = FMPCreateTable.convertFromUTF8(value); if (value.length() <= fd.getMaxSize()) { pStmt.setString(col, value); } else { System.err.println(String.format("The data for `%s` max(%d) is too big %d", fd.getName(), fd.getMaxSize(), value.length())); pStmt.setString(col, null); } } else { pStmt.setString(col, null); } } break; case eNumber: { if (StringUtils.isNotEmpty(value)) { String origValue = value; String val = value.charAt(0) == '' ? value.substring(1) : value; val = val.charAt(0) == '-' ? val.substring(1) : val; val = val.indexOf('.') > -1 ? StringUtils.replace(val, ".", "") : val; val = val.indexOf('') > -1 ? StringUtils.replace(val, "", "") : val; if (StringUtils.isNumericSpace(val)) { if (fd.isDouble()) { pStmt.setDouble(col, Double.parseDouble(val)); } else { pStmt.setInt(col, Integer.parseInt(val)); } } else if (val.startsWith("ca. ")) { pStmt.setInt(col, Integer.parseInt(val.substring(4))); } else if (val.startsWith("ca ")) { pStmt.setInt(col, Integer.parseInt(val.substring(3))); } else { System.err.println(col + " Bad Number val[" + val + "] origValue[" + origValue + "] " + fieldDefs.get(col - 1).getName()); pStmt.setObject(col, null); } } else { pStmt.setDate(col, null); } } break; case eTime: { Time time = null; try { time = Time.valueOf(value); } catch (Exception ex) { } pStmt.setTime(col, time); } break; case eDate: { String origValue = value; try { if (StringUtils.isNotEmpty(value) && !value.equals("?") && !value.equals("-")) { int len = value.length(); if (len == 8 && value.charAt(1) == '-' && value.charAt(3) == '-') // 0-9-1886 { String dayStr = value.substring(0, 1); String monStr = value.substring(2, 3); if (StringUtils.isNumeric(dayStr) && StringUtils.isNumeric(monStr)) { String year = value.substring(4); int day = Integer.parseInt(dayStr); int mon = Integer.parseInt(monStr); if (day == 0) day = 1; if (mon == 0) mon = 1; value = String.format("%02d-%02d-%s", day, mon, year); } else { value = StringUtils.replaceChars(value, '.', ' '); String[] toks = StringUtils.split(value, ' '); if (toks.length == 3) { String dyStr = toks[0]; String mnStr = toks[1]; String yrStr = toks[2]; if (StringUtils.isNumeric(mnStr) && StringUtils.isNumeric(dyStr) && StringUtils.isNumeric(yrStr)) { int day = Integer.parseInt(dyStr); int mon = Integer.parseInt(mnStr); int year = Integer.parseInt(yrStr); if (day == 0) day = 1; if (mon == 0) mon = 1; value = String.format("%02d-%02d-%04d", day, mon, year); } else { System.err.println( col + " Bad Date#[" + value + "] [" + origValue + "]\n"); } } else { System.err.println( col + " Bad Date#[" + value + "] [" + origValue + "]\n"); } } } else if (len == 8 && (value.charAt(3) == '-' || value.charAt(3) == ' ')) // Apr-1886 { String monStr = value.substring(0, 3); Integer month = monthHash.get(monStr); String year = value.substring(4); if (month != null && StringUtils.isNumeric(year)) { value = String.format("01-%02d-%s", month, year); } else { value = StringUtils.replaceChars(value, '.', ' '); String[] toks = StringUtils.split(value, ' '); if (toks.length == 3) { String dyStr = toks[0]; String mnStr = toks[1]; String yrStr = toks[2]; if (StringUtils.isNumeric(mnStr) && StringUtils.isNumeric(dyStr) && StringUtils.isNumeric(yrStr)) { int day = Integer.parseInt(dyStr); int mon = Integer.parseInt(mnStr); int yr = Integer.parseInt(yrStr); if (day == 0) day = 1; if (mon == 0) mon = 1; value = String.format("%02d-%02d-%04d", day, mon, yr); } else { System.err.println( col + " Bad Date#[" + value + "] [" + origValue + "]\n"); } } else { System.err.println( col + " Bad Date#[" + value + "] [" + origValue + "]\n"); } } } else if ((len == 11 && value.charAt(2) == '-' && value.charAt(6) == '-') || // 10-May-1898 (len == 10 && value.charAt(1) == '-' && value.charAt(5) == '-')) // 7-May-1898 { boolean do11 = len == 11; String dayStr = value.substring(0, do11 ? 2 : 1); String monStr = value.substring(do11 ? 3 : 2, do11 ? 6 : 5); Integer month = monthHash.get(monStr); String year = value.substring(do11 ? 7 : 6); if (month != null && StringUtils.isNumeric(dayStr) && StringUtils.isNumeric(year)) { int day = Integer.parseInt(dayStr); if (day == 0) day = 1; value = String.format("%02d-%02d-%s", day, month, year); } else { System.err .println(col + " Bad Date^[" + value + "] [" + origValue + "]\n"); } } else if (len == 4) { if (StringUtils.isNumeric(value)) { value = "01-01-" + value; } else if (value.equalsIgnoreCase("s.d.") || value.equalsIgnoreCase("n.d.") || value.equalsIgnoreCase("s.n.")) { value = null; } } else if (StringUtils.contains(value, "/")) { value = StringUtils.replace(value, "/", "-"); } else if (StringUtils.contains(value, " ")) { value = StringUtils.replace(value, " ", "-"); } pStmt.setDate(col, StringUtils.isNotEmpty(value) ? new java.sql.Date(sdf.parse(value).getTime()) : null); } else { pStmt.setDate(col, null); } } catch (Exception ex) { System.err.println(col + " Bad Date[" + value + "] [" + origValue + "]\n" + str); pStmt.setDate(col, null); } } break; default: { System.err.println("Col: " + col + " Error - " + fd.getType()); } } inx++; col++; } pStmt.execute(); str = in.readLine(); rowCnt++; if (rowCnt % 1000 == 0) { System.out.println(rowCnt); } } in.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { stmt.close(); conn.close(); pStmt.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
From source file:com.ibm.xsp.webdav.resource.DAVResourceDominoAttachments.java
private void fetchChildrenForNotesDocument() { LOGGER.debug("Fetching children for " + this.getName()); Document curDoc = null;/*from w w w.ja v a 2 s . c o m*/ String docID = null; Vector<IDAVResource> resMembers = new Vector<IDAVResource>(); String notesURL = this.getInternalAddress(); curDoc = DominoProxy.getDocument(notesURL); if (curDoc == null) { LOGGER.error("Could not retrieve the document"); return; } // Read the repository list to get the view try { docID = curDoc.getUniversalID(); LOGGER.debug("Openend document " + docID); // No children if there are no attachments if (!curDoc.hasEmbedded()) { // E.C. It is a directory, so fetch the children documents as // resources LOGGER.error("Current doc with unid=" + curDoc.getUniversalID() + " has no embedded files. Try to find children"); DocumentCollection responses = curDoc.getResponses(); int numOfResponses = responses.getCount(); if (numOfResponses > 0) { LOGGER.error("Current doc has " + numOfResponses + " responses"); Document docResp = responses.getFirstDocument(); while (docResp != null) { LOGGER.error("Doc response has unid=" + docResp.getUniversalID()); @SuppressWarnings("rawtypes") Vector allEmbedded = DominoProxy.evaluate("@AttachmentNames", docResp); int numOfAttchments = allEmbedded.size(); if (numOfAttchments == 0) { // No attachments in here! LOGGER.error("Doc response has no attachment; is a directory"); LOGGER.debug(docID + " has no attachments (@AttachmentNames)"); // embed // as // doc DAVResourceDominoAttachments resAtt = getDocumentResource(docResp); if (resAtt != null) { LOGGER.error("Created DavResourceDomino Attachments from getDocumentResource-OK"); resMembers.add(resAtt); LOGGER.error("Resource successfull added"); } else { LOGGER.error( "Problem, DavResourceDomino Attachments from getDocumentResource- FAILED"); } } else { LOGGER.error("Doc response has attachments;"); String curAttName = allEmbedded.get(0).toString(); DAVResourceDominoAttachments curAttachment = getAttachmentResource(this.isReadOnly(), docResp, curAttName); if (curAttachment != null) { // Now add it to the Vector LOGGER.error("Created DavResourceDominoAttachments with getAttachmentResource-OK"); resMembers.add(curAttachment); LOGGER.error("Resource successfull added"); Date viewDate = this.getLastModified(); Date docDate = curAttachment.getLastModified(); if (viewDate == null || (docDate != null && viewDate.before(docDate))) { this.setLastModified(docDate); } LOGGER.error("Resource successfull updated last modified"); LOGGER.debug("Processing complete attachment " + curAttName); } else { LOGGER.error("Could not load attachment " + curAttName); } } Document docTmp = docResp; docResp = responses.getNextDocument(docResp); docTmp.recycle(); } // end while } // end if numresp>0 try { if (curDoc != null) { curDoc.recycle(); } } catch (Exception e) { LOGGER.error(e); } // Now save back the members to the main object this.setMembers(resMembers); return; } // Get all attachments @SuppressWarnings("rawtypes") Vector allEmbedded = DominoProxy.evaluate("@AttachmentNames", curDoc); int numOfAttchments = allEmbedded.size(); if (numOfAttchments == 0) { // No attachments in here! LOGGER.debug(docID + " has no attachments (@AttachmentNames)"); return; } LOGGER.debug(docID + " has " + new Integer(numOfAttchments).toString() + " attachment(s)"); // Initialize an empty vector at the right size // We might need to enlarge it if we have more attachments resMembers = new Vector<IDAVResource>(numOfAttchments); for (int i = 0; i < numOfAttchments; i++) { String curAttName = allEmbedded.get(i).toString(); DAVResourceDominoAttachments curAttachment = getAttachmentResource(this.isReadOnly(), curDoc, curAttName); if (curAttachment != null) { // Now add it to the Vector resMembers.add(curAttachment); LOGGER.debug("Processing complete attachment " + curAttName); } else { LOGGER.error("Could not load attachment " + curAttName); } } } catch (NotesException ne) { LOGGER.error(ne); } catch (Exception e) { LOGGER.error(e); } finally { try { if (curDoc != null) { curDoc.recycle(); } } catch (Exception e) { LOGGER.error(e); } // Now save back the members to the main object this.setMembers(resMembers); LOGGER.debug("Completed reading attachments resources from Notes document"); } }
From source file:imapi.OnlineDatabaseActions.java
int getUris(String query, Vector<String> mergeVals) { InputStream answerStream = performDatabaseQuery(query); if (answerStream == null) { return ApiConstants.IMAPIFailCode; }/* w ww.j a v a 2s .c o m*/ Vector<String> tempVec = new Vector<String>(); int ret = this.readJsonUriVals(answerStream, tempVec); if (ret != ApiConstants.IMAPISuccessCode) { return ret; } for (int i = 0; i < tempVec.size(); i++) { String val = tempVec.get(i); if (mergeVals.contains(val) == false) { mergeVals.add(val); } } return ApiConstants.IMAPISuccessCode; }
From source file:com.sos.VirtualFileSystem.SFTP.SOSVfsSFtp.java
@Override public String[] listNames(String pathname) throws IOException { pathname = resolvePathname(pathname); try {// w w w .j ava2 s . c o m if (pathname.length() == 0) pathname = "."; if (!fileExists(pathname)) return null; if (!isDirectory(pathname)) { File remoteFile = new File(pathname); reply = "ls OK"; return new String[] { remoteFile.getName() }; } @SuppressWarnings("unchecked") Vector<SFTPv3DirectoryEntry> files = Client().ls(pathname); String[] rvFiles = new String[files.size()]; for (int i = 0; i < files.size(); i++) { SFTPv3DirectoryEntry entry = files.get(i); rvFiles[i] = addFileSeparator(pathname) + entry.filename; } reply = "ls OK"; return rvFiles; } catch (Exception e) { reply = e.toString(); return null; } }
From source file:com.duroty.application.files.manager.StoreManager.java
/** * DOCUMENT ME!//from w w w. ja v a2 s. c o m * * @param hsession DOCUMENT ME! * @param session DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param identity DOCUMENT ME! * @param to DOCUMENT ME! * @param cc DOCUMENT ME! * @param bcc DOCUMENT ME! * @param subject DOCUMENT ME! * @param body DOCUMENT ME! * @param attachments DOCUMENT ME! * @param isHtml DOCUMENT ME! * @param charset DOCUMENT ME! * @param headers DOCUMENT ME! * @param priority DOCUMENT ME! * * @throws MailException DOCUMENT ME! */ public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files, int label, String charset) throws FilesException { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { if ((files == null) || (files.size() <= 0)) { return; } if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } Users user = getUser(hsession, repositoryName); Identity identity = getDefaultIdentity(hsession, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); for (int i = 0; i < files.size(); i++) { MultiPartEmail email = email = new MultiPartEmail(); email.setCharset(charset); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if (_to != null) { email.addTo(_to.getAddress(), _to.getPersonal()); } MailPartObj obj = (MailPartObj) files.get(i); email.setSubject("Files-System " + obj.getName()); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); email.attach(attachment); String mid = getId(); email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader("X-DBox", "FILES"); email.addHeader("X-DRecent", "false"); //email.setMsg(body); email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeMessage(mid, mime, user); } } catch (FilesException e) { throw e; } catch (Exception e) { throw new FilesException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new FilesException(ex); } catch (Throwable e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } }
From source file:helma.framework.core.Application.java
/** * This is called to shut down a running application. *///from ww w . j a v a 2 s . com public synchronized void stop() { // invoke global onStop() function RequestEvaluator eval = null; try { eval = getEvaluator(); eval.invokeInternal(null, "onStop", RequestEvaluator.EMPTY_ARGS); } catch (Exception x) { logError("Error in " + name + ".onStop()", x); } // mark app as stopped running = false; // stop all threads, this app is going down if (worker != null) { worker.interrupt(); } worker = null; // stop evaluators if (allThreads != null) { for (Enumeration e = allThreads.elements(); e.hasMoreElements();) { RequestEvaluator ev = (RequestEvaluator) e.nextElement(); ev.stopTransactor(); ev.shutdown(); } } // remove evaluators allThreads.removeAllElements(); freeThreads.clear(); // shut down node manager and embedded db try { nmgr.shutdown(); } catch (DatabaseException dbx) { System.err.println("Error shutting down embedded db: " + dbx); } // tell the extensions that we're stopped. if (Server.getServer() != null) { Vector extensions = Server.getServer().getExtensions(); for (int i = 0; i < extensions.size(); i++) { HelmaExtension ext = (HelmaExtension) extensions.get(i); ext.applicationStopped(this); } } // store the sessions if wanted if ("true".equalsIgnoreCase(getProperty("persistentSessions"))) { // sessionMgr.storeSessionData(null); sessionMgr.storeSessionData(null, eval.scriptingEngine); } sessionMgr.shutdown(); }
From source file:helma.framework.core.Application.java
private synchronized void updateProperties() { // if so property file has been updated, re-read props. if (props.lastModified() > lastPropertyRead) { // force property update props.update();// ww w . j a v a 2 s . c om // character encoding to be used for responses charset = props.getProperty("charset", "UTF-8"); // debug flag debug = "true".equalsIgnoreCase(props.getProperty("debug")); // if rhino debugger is enabled use higher (10 min) default request timeout String defaultReqTimeout = "true".equalsIgnoreCase(props.getProperty("rhino.debug")) ? "600" : "60"; String reqTimeout = props.getProperty("requesttimeout", defaultReqTimeout); try { requestTimeout = Long.parseLong(reqTimeout) * 1000L; } catch (Exception ignore) { // go with default value requestTimeout = 60000L; } // set base URI String base = props.getProperty("baseuri"); if (base != null) { setBaseURI(base); } else if (baseURI == null) { baseURI = "/"; } hrefRootPrototype = props.getProperty("hrefrootprototype"); rootObjectPropertyName = props.getProperty("rootobjectpropertyname"); rootObjectFunctionName = props.getProperty("rootobjectfunctionname"); // update the XML-RPC access list, containting prototype.method // entries of functions that may be called via XML-RPC String xmlrpcAccessProp = props.getProperty("xmlrpcaccess"); HashSet xra = new HashSet(); if (xmlrpcAccessProp != null) { StringTokenizer st = new StringTokenizer(xmlrpcAccessProp, ",; "); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); xra.add(token.toLowerCase()); } } xmlrpcAccess = xra; // if node manager exists, update it if (nmgr != null) { nmgr.updateProperties(props); } // update extensions if (Server.getServer() != null) { Vector extensions = Server.getServer().getExtensions(); for (int i = 0; i < extensions.size(); i++) { HelmaExtension ext = (HelmaExtension) extensions.get(i); try { ext.applicationUpdated(this); } catch (ConfigurationException e) { logEvent("Error updating extension " + ext + ": " + e); } } } String loggerFactory = props.getProperty("loggerFactory", "helma.util.Logging"); if ("helma.util.Logging".equals(loggerFactory)) { logDir = props.getProperty("logdir", "log"); if (System.getProperty("helma.logdir") == null) { // set up helma.logdir system property in case we're using it // FIXME: this sets a global System property, should be per-app File dir = new File(logDir); System.setProperty("helma.logdir", dir.getAbsolutePath()); } } else { logDir = null; } // set log level for event log in case debug flag has changed setEventLogLevel(); // set prop read timestamp lastPropertyRead = props.lastModified(); } }