List of usage examples for java.lang StringBuffer substring
@Override public synchronized String substring(int start, int end)
From source file:org.wso2.carbon.es.migration.MigrationDatabaseCreator.java
/** * executes content in SQL script// w w w .j a v a 2s. c om * * @throws IOException,SQLException */ private void executeSQLScript(String dbscriptName) throws IOException, SQLException { String delimiter = ";"; boolean keepFormat = false; StringBuffer sql = new StringBuffer(); try (InputStream is = getClass().getResourceAsStream(dbscriptName); InputStreamReader inputStreamReader = new InputStreamReader(is); BufferedReader reader = new BufferedReader(inputStreamReader)) { String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!keepFormat) { if (line.startsWith("//")) { continue; } if (line.startsWith("--")) { continue; } StringTokenizer st = new StringTokenizer(line); if (st.hasMoreTokens()) { String token = st.nextToken(); if ("REM".equalsIgnoreCase(token)) { continue; } } } sql.append(keepFormat ? "\n" : " ").append(line); if (!keepFormat && line.indexOf("--") >= 0) { sql.append("\n"); } if ((DatabaseCreator.checkStringBufferEndsWith(sql, delimiter))) { executeSQL(sql.substring(0, sql.length() - delimiter.length())); sql.replace(0, sql.length(), ""); } } if (sql.length() > 0) { executeSQL(sql.toString()); } } }
From source file:org.wso2.carbon.greg.migration.MigrationDatabaseCreator.java
/** * executes content in SQL script/*w w w . j a v a 2 s .co m*/ * * @throws Exception */ private void executeSQLScript(String dbscriptName) throws IOException, SQLException { boolean keepFormat = false; StringBuffer sql = new StringBuffer(); BufferedReader reader = null; try { InputStream is = getClass().getResourceAsStream(dbscriptName); reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!keepFormat) { if (line.startsWith("//")) { continue; } if (line.startsWith("--")) { continue; } StringTokenizer st = new StringTokenizer(line); if (st.hasMoreTokens()) { String token = st.nextToken(); if ("REM".equalsIgnoreCase(token)) { continue; } } } sql.append(keepFormat ? "\n" : " ").append(line); if (!keepFormat && line.indexOf("--") >= 0) { sql.append("\n"); } if ((DatabaseCreator.checkStringBufferEndsWith(sql, delimiter))) { executeSQL(sql.substring(0, sql.length() - delimiter.length())); sql.replace(0, sql.length(), ""); } } if (sql.length() > 0) { executeSQL(sql.toString()); } } finally { if (reader != null) { reader.close(); } } }
From source file:org.wso2.carbon.greg.migration.MigrationDatabaseCreator.java
/** * executes content in idp & sp SQL scripts * * @throws Exception//from w ww . j av a 2 s. c om */ private void executeIdentitySQLScript(String dbscriptName) throws Exception { String databaseType = DatabaseCreator.getDatabaseType(this.conn); boolean keepFormat = false; if (Constants.DatabaseTypes.oracle.toString().equals(databaseType)) { delimiter = "/"; } else if (Constants.DatabaseTypes.db2.toString().equals(databaseType)) { delimiter = "/"; } else if ("openedge".equals(databaseType)) { delimiter = "//"; keepFormat = true; } StringBuffer sql = new StringBuffer(); BufferedReader reader = null; try { InputStream is = getClass().getResourceAsStream(dbscriptName); reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!keepFormat) { if (line.startsWith("//")) { continue; } if (line.startsWith("--")) { continue; } StringTokenizer st = new StringTokenizer(line); if (st.hasMoreTokens()) { String token = st.nextToken(); if ("REM".equalsIgnoreCase(token)) { continue; } } } sql.append(keepFormat ? "\n" : " ").append(line); if (!keepFormat && line.indexOf("--") >= 0) { sql.append("\n"); } if ((DatabaseCreator.checkStringBufferEndsWith(sql, delimiter))) { executeSQL(sql.substring(0, sql.length() - delimiter.length())); sql.replace(0, sql.length(), ""); } } if (sql.length() > 0) { executeSQL(sql.toString()); } } finally { if (reader != null) { reader.close(); } } }
From source file:org.ambraproject.service.article.BrowseServiceImpl.java
/** * Returns list of articles in a given date range, from newest to oldest * @param params the collection class of parameters. * @return the articles//from w w w.ja v a2 s . c o m */ private BrowseResult getArticlesByDateViaSolr(BrowseParameters params) { BrowseResult result = new BrowseResult(); ArrayList<SearchHit> articles = new ArrayList<SearchHit>(); long totalSize = 0; SolrQuery query = createCommonQuery(params.getJournalKey()); query.addField("title_display"); query.addField("author_display"); query.addField("article_type"); query.addField("publication_date"); query.addField("id"); query.addField("abstract_primary_display"); query.addField("eissn"); query.addField("striking_image"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String sDate = sdf.format(params.getStartDate().getTime()); String eDate = sdf.format(params.getEndDate().getTime()); sDate = sDate + "T00:00:00Z"; eDate = eDate + "T00:00:00Z"; query.addFilterQuery("publication_date:[" + sDate + " TO " + eDate + "]"); StringBuffer sb = new StringBuffer(); if (params.getArticleTypes() != null && params.getArticleTypes().size() > 0) { for (URI uri : params.getArticleTypes()) { String path = uri.getPath(); int index = path.lastIndexOf("/"); if (index != -1) { String articleType = path.substring(index + 1); sb.append("\"").append(articleType).append("\"").append(" OR "); } } String articleTypesQuery = sb.substring(0, sb.length() - 4); if (articleTypesQuery.length() > 0) { query.addFilterQuery("article_type_facet:" + articleTypesQuery); } } setSort(query, params); query.setStart(params.getPageNum() * params.getPageSize()); query.setRows(params.getPageSize()); log.info("getArticlesByDate Solr Query:" + query.toString()); try { QueryResponse response = this.serverFactory.getServer().query(query); SolrDocumentList documentList = response.getResults(); totalSize = documentList.getNumFound(); for (SolrDocument document : documentList) { SearchHit sh = createArticleBrowseDisplay(document, query.toString()); articles.add(sh); } } catch (SolrServerException e) { log.error("Unable to execute a query on the Solr Server.", e); } result.setArticles(articles); result.setTotal(totalSize); return result; }
From source file:Comments.java
public static String removeComment(String input) { StringBuffer sb = new StringBuffer(input); char NQ = ' ', quote = NQ; int len = sb.length(); for (int j = 0, lineno = 1; j < len; j++) { if (sb.charAt(j) == '\n') ++lineno;//from w w w . ja va 2 s.c o m if (quote != NQ) { if (sb.charAt(j) == quote) { quote = NQ; } else if (sb.charAt(j) == '\\') { j++; //fix for "123\\\r\n123" if (sb.charAt(j) == '\r') j++; // if(sb.charAt(j) == '\n') j++; } else if (sb.charAt(j) == '\n') { throw new IllegalStateException("Unterminated string at line " + lineno); } } else if (sb.charAt(j) == '/' && j + 1 < len && (sb.charAt(j + 1) == '*' || sb.charAt(j + 1) == '/')) { int l = j; boolean eol = sb.charAt(++j) == '/'; while (++j < len) { if (sb.charAt(j) == '\n') ++lineno; if (eol) { if (sb.charAt(j) == '\n') { sb.delete(l, sb.charAt(j - 1) == '\r' ? j - 1 : j); len = sb.length(); j = l; break; } } else if (sb.charAt(j) == '*' && j + 1 < len && sb.charAt(j + 1) == '/') { sb.delete(l, j + 2); len = sb.length(); j = l; break; } } } else if (sb.charAt(j) == '\'' || sb.charAt(j) == '"') { quote = sb.charAt(j); } else if (sb.charAt(j) == '/') { // regex boolean regex = false; for (int k = j;;) { if (--k < 0) { regex = true; break; } char ck = sb.charAt(k); if (!Character.isWhitespace(ck)) { regex = ck == '(' || ck == ',' || ck == '=' || ck == ':' || ck == '?' || ck == '{' || ck == '[' || ck == ';' || ck == '!' || ck == '&' || ck == '|' || ck == '^' || (ck == 'n' && k > 4 && "return".equals(sb.substring(k - 5, k + 1))) || (ck == 'e' && k > 2 && "case".equals(sb.substring(k - 3, k + 1))); break; } } if (regex) { while (++j < len && sb.charAt(j) != '/') { if (sb.charAt(j) == '\\') j++; else if (sb.charAt(j) == '\n') { throw new IllegalStateException("Unterminated regex at line " + lineno); } } } } } return sb.toString(); }
From source file:cn.future.ssh.service.impl.AccreditationServiceImpl.java
/** * ????????????????//from w w w . j a va 2 s.co m */ @Override public void submitAccreditation(AccreditationBean accreditationBean) { Accreditation accreditation = null; Personnel loader = SessionContext.get(); Squadron squadron = loader.getSquadron(); Long accreditationId = accreditationBean.getAccreditationId(); if (accreditationId == null) { accreditation = new Accreditation(); } else { accreditation = accreditationDao.findAccreditationByAccreditationId(accreditationId); } Map<String, Object> variables = new HashMap<String, Object>(); accreditation.setId(accreditationBean.getAccreditationId()); // Summary summary = new Summary(); summary.setId(accreditationBean.getSummaryId()); accreditation.setSummary(summary); // ?? accreditation.setUnitName(accreditationBean.getUnitName()); accreditation.setLeRepresentative(accreditationBean.getLeRepresentative()); accreditation.setUnitTel(accreditationBean.getUnitTel()); accreditation.setUnitAddress(accreditationBean.getUnitAddress()); // accreditation.setPersonnelName(accreditationBean.getPersonnelName()); if (accreditationBean.getUnitName() == null || "".equals(accreditationBean.getUnitName().trim())) { accreditation.setSex(accreditationBean.getSex()); accreditation.setUserAge(accreditationBean.getUserAge()); accreditation.setUserAddress(accreditationBean.getUserAddress()); accreditation.setIdNumber(accreditationBean.getIdNumber()); accreditation.setUserTel(accreditationBean.getUserTel()); } // accreditation.setBaseCase(accreditationBean.getBaseCase()); // ?? CaseSource caseSource = new CaseSource(); caseSource.setId(accreditationBean.getCaseSourceId()); accreditation.setCaseSource(caseSource); // accreditation.setLegGuideSuggest(accreditationBean.getLegGuideSuggest()); // ?? Personnel sponsor = new Personnel(); Long sponsorId = accreditationBean.getSponsorId(); sponsor.setId(sponsorId); Long assistantHandleId = accreditationBean.getAssistantHandleId(); Personnel assistantHandle = new Personnel(); assistantHandle.setId(assistantHandleId); accreditation.setSponsor(sponsor); accreditation.setAssistantHandle(assistantHandle); // /*String imagePath = "document"; String fullPath = ServletActionContext.getServletContext().getRealPath( imagePath); */ /*String imagePath = "document"; String fullPath = ServletActionContext.getServletContext().getRealPath( ""); fullPath = fullPath+"/..";*/ if (accreditationBean.getTaskId() == null || "".equals(accreditationBean.getTaskId())) { accreditationDao.saveAccreditation(accreditation); } String imagePath = "e:" + ServletActionContext.getRequest().getContextPath() + "/document/" + accreditation.getId(); File imagesSavedir = new File(imagePath); if (!imagesSavedir.exists()) { imagesSavedir.mkdirs(); } // ??? ArrayList<String> allowType = new ArrayList<String>(); for (Object key : properties.keySet()) { String value = (String) properties.get(key); String[] values = value.split(","); for (String v : values) { allowType.add(v); } } File idCardFile = accreditationBean.getIdCard(); if (idCardFile != null) { String idCardFileName = accreditationBean.getIdCardFileName(); if (!allowType.contains(accreditationBean.getIdCardContentType().toLowerCase()) || properties.keySet() .contains(idCardFileName.substring(idCardFileName.lastIndexOf(",") + 1))) { try { throw new Exception(""); } catch (Exception e) { e.printStackTrace(); } return; } String ext = idCardFileName.substring(idCardFileName.lastIndexOf(".")); Document idCard = new Document(); String imageName = UUID.randomUUID().toString() + ext; idCard.setImageName(imageName); idCard.setAccreditation(accreditation); //? documentService.saveDocument(idCard); File outputDir = new File(imagesSavedir, imageName); FileInputStream is; try { FileOutputStream os = new FileOutputStream(outputDir); is = new FileInputStream(idCardFile); int length; byte[] buffer = new byte[1024 * 1024]; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } os.close(); is.close(); } catch (Exception e) { e.printStackTrace(); } accreditation.setIdCard(idCard); } File businessLicese = accreditationBean.getBusinessLicense(); if (businessLicese != null) { String businessLicenseFileName = accreditationBean.getBusinessLicenseFileName(); if (!allowType.contains(accreditationBean.getBusinessLicenseContentType().toLowerCase()) || properties.keySet().contains( businessLicenseFileName.substring(businessLicenseFileName.lastIndexOf(",") + 1))) { try { throw new Exception(""); } catch (Exception e) { e.printStackTrace(); } return; } String ext = businessLicenseFileName.substring(businessLicenseFileName.lastIndexOf(".")); Document businessLicense = new Document(); String imageName = UUID.randomUUID().toString() + ext; businessLicense.setImageName(imageName); businessLicense.setAccreditation(accreditation); //? documentService.saveDocument(businessLicense); File outputDir = new File(imagesSavedir, imageName); FileInputStream is; try { FileOutputStream os = new FileOutputStream(outputDir); is = new FileInputStream(idCardFile); int length; byte[] buffer = new byte[1024 * 1024]; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } os.close(); is.close(); } catch (Exception e) { e.printStackTrace(); } accreditation.setBusinessLicense(businessLicense); } saveDocument(accreditation, accreditationBean, "EnforceCard", allowType, imagesSavedir); saveDocument(accreditation, accreditationBean, "OrderChangeNotice", allowType, imagesSavedir); saveDocument(accreditation, accreditationBean, "RecordInquest", allowType, imagesSavedir); saveDocument(accreditation, accreditationBean, "SitePhotos", allowType, imagesSavedir); saveDocument(accreditation, accreditationBean, "RecordInv", allowType, imagesSavedir); saveDocument(accreditation, accreditationBean, "RecordPaper", allowType, imagesSavedir); variables.put("sponsorId", Long.toString(accreditation.getSponsor().getId())); variables.put("assistantHandleId", Long.toString(accreditation.getAssistantHandle().getId())); if (accreditationBean.getTaskId() == null || "".equals(accreditationBean.getTaskId())) { // ??? Personnel captain = personnelService.findCaptainByMember(loader); variables.put("captainId", Long.toString(captain.getId())); // ??? Personnel bigCaptain = personnelService.findPersonByRole(""); variables.put("bigCaptainId", Long.toString(bigCaptain.getId())); // ? variables.put("accreditationSubmit", "false"); variables.put("pTableSubmit", "false"); variables.put("pClosingReportSubmit", "false"); // List<Personnel> legalDepartmentPersonnels = personnelService.findLegalDepartmentPersonnels(); StringBuffer legalDepartmentPersonnelsIds = new StringBuffer(); for (Personnel personnel : legalDepartmentPersonnels) { legalDepartmentPersonnelsIds.append(Long.toString(personnel.getId()) + ","); } variables.put("legalDepartmentPersonnelsIds", legalDepartmentPersonnelsIds.substring(0, legalDepartmentPersonnelsIds.length() - 1)); // ? variables.put("legalDepartmentPersonnelId", null); // List<Personnel> industryCommitteePersonnels = personnelService.findIndustryCommitteePersonnels(); List<String> industryCommitteePersonnelsIds = new ArrayList<String>(); for (Personnel personnel : industryCommitteePersonnels) { industryCommitteePersonnelsIds.add(Long.toString(personnel.getId())); } variables.put("industryCommitteePersonnelsIds", industryCommitteePersonnelsIds); // StringBuffer ownersCommitteePersonnelsIds = new StringBuffer(); for (Personnel personnel : industryCommitteePersonnels) { ownersCommitteePersonnelsIds.append(Long.toString(personnel.getId()) + ","); } variables.put("ownersCommitteePersonnelsIds", ownersCommitteePersonnelsIds.substring(0, ownersCommitteePersonnelsIds.length() - 1)); /* * //? variables.put("ownersCommitteePersonnelId", * null); */ // List<Personnel> caseReviewComPersonnels = personnelService.findCaseReviewComPersonnels(); List<String> caseReviewComPersonnelsIds = new ArrayList<String>(); for (Personnel personnel : caseReviewComPersonnels) { caseReviewComPersonnelsIds.add(Long.toString(personnel.getId())); } variables.put("caseReviewComPersonnelsIds", caseReviewComPersonnelsIds); String key = accreditation.getClass().getSimpleName(); String objId = key + "." + accreditation.getId(); variables.put("squadronId", "squadron" + Long.toString(squadron.getId())); // ?? runtimeService.startProcessInstanceByKey(key, objId, variables); Task task = taskService.createTaskQuery().taskAssignee("squadron" + Long.toString(squadron.getId())) .orderByTaskCreateTime().desc().list().get(0); taskService.complete(task.getId(), variables); } else { accreditation.setId(accreditationBean.getAccreditationId()); accreditationDao.updateAccreditation(accreditation); taskService.complete(accreditationBean.getTaskId(), variables); } accreditation.setSquadron(squadron); accreditationDao.updateAccreditation(accreditation); squadron.getAccreditation().add(accreditation); squadronService.updateSquadron(squadron); }
From source file:info.magnolia.cms.beans.config.PropertiesInitializer.java
/** * Parse the given String value recursively, to be able to resolve nested placeholders. Partly borrowed from * org.springframework.beans.factory.config.PropertyPlaceholderConfigurer (original author: Juergen Hoeller) * * @deprecated since 4.5 this is now done by {@link info.magnolia.init.AbstractMagnoliaConfigurationProperties#parseStringValue}. *///from w w w . j a v a 2 s .c o m protected String parseStringValue(String strVal, Set<String> visitedPlaceholders) { StringBuffer buf = new StringBuffer(strVal); int startIndex = strVal.indexOf(PLACEHOLDER_PREFIX); while (startIndex != -1) { int endIndex = -1; int index = startIndex + PLACEHOLDER_PREFIX.length(); int withinNestedPlaceholder = 0; while (index < buf.length()) { if (PLACEHOLDER_SUFFIX.equals(buf.subSequence(index, index + PLACEHOLDER_SUFFIX.length()))) { if (withinNestedPlaceholder > 0) { withinNestedPlaceholder--; index = index + PLACEHOLDER_SUFFIX.length(); } else { endIndex = index; break; } } else if (PLACEHOLDER_PREFIX.equals(buf.subSequence(index, index + PLACEHOLDER_PREFIX.length()))) { withinNestedPlaceholder++; index = index + PLACEHOLDER_PREFIX.length(); } else { index++; } } if (endIndex != -1) { String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex); if (!visitedPlaceholders.add(placeholder)) { log.warn("Circular reference detected in properties, \"{}\" is not resolvable", strVal); return strVal; } // Recursive invocation, parsing placeholders contained in the placeholder key. placeholder = parseStringValue(placeholder, visitedPlaceholders); // Now obtain the value for the fully resolved key... String propVal = SystemProperty.getProperty(placeholder); if (propVal != null) { // Recursive invocation, parsing placeholders contained in the // previously resolved placeholder value. propVal = parseStringValue(propVal, visitedPlaceholders); buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal); startIndex = buf.indexOf(PLACEHOLDER_PREFIX, startIndex + propVal.length()); } else { // Proceed with unprocessed value. startIndex = buf.indexOf(PLACEHOLDER_PREFIX, endIndex + PLACEHOLDER_SUFFIX.length()); } visitedPlaceholders.remove(placeholder); } else { startIndex = -1; } } return buf.toString(); }
From source file:org.jivesoftware.community.util.StringUtils.java
public static String wordWrap(String input, int width, Locale locale) { if (input == null) return ""; if (width < 5) return input; if (width >= input.length()) return input; if (locale == null) locale = JiveGlobals.getLocale(); StringBuffer buf = new StringBuffer(input); boolean endOfLine = false; int lineStart = 0; for (int i = 0; i < buf.length(); i++) { if (buf.charAt(i) == '\n') { lineStart = i + 1;//from ww w.ja v a2 s . com endOfLine = true; } if (i <= (lineStart + width) - 1) continue; if (!endOfLine) { int limit = i - lineStart - 1; BreakIterator breaks = BreakIterator.getLineInstance(locale); breaks.setText(buf.substring(lineStart, i)); int end = breaks.last(); if (end == limit + 1 && !Character.isWhitespace(buf.charAt(lineStart + end))) end = breaks.preceding(end - 1); if (end != -1 && end == limit + 1) { buf.replace(lineStart + end, lineStart + end + 1, "\n"); lineStart += end; continue; } if (end != -1 && end != 0) { buf.insert(lineStart + end, '\n'); lineStart = lineStart + end + 1; } else { buf.insert(i, '\n'); lineStart = i + 1; } } else { buf.insert(i, '\n'); lineStart = i + 1; endOfLine = false; } } return buf.toString(); }
From source file:org.wso2.carbon.apimgt.migration.client.MigrationDBCreator.java
private void executeSQLScript() throws Exception { String databaseType = DatabaseCreator.getDatabaseType(this.connection); boolean keepFormat = false; if (Constants.DB_TYPE_ORACLE.equals(databaseType)) { delimiter = "/"; } else if (Constants.DB_TYPE_DB2.equals(databaseType)) { delimiter = "/"; } else if (Constants.DB_TYPE_OPENEDGE.equals(databaseType)) { delimiter = "/"; keepFormat = true;/*from www .jav a2 s . co m*/ } String dbscriptName = getDbScriptLocation(databaseType); StringBuffer sql = new StringBuffer(); BufferedReader reader = null; try { InputStream is = new FileInputStream(dbscriptName); reader = new BufferedReader(new InputStreamReader(is, "UTF8")); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!keepFormat) { if (line.startsWith("//")) { continue; } if (line.startsWith("--")) { continue; } StringTokenizer st = new StringTokenizer(line); if (st.hasMoreTokens()) { String token = st.nextToken(); if ("REM".equalsIgnoreCase(token)) { continue; } } } sql.append(keepFormat ? "\n" : " ").append(line); // SQL defines "--" as a comment to EOL // and in Oracle it may contain a hint // so we cannot just remove it, instead we must end it if (!keepFormat && line.indexOf("--") >= 0) { sql.append('\n'); } if ((checkStringBufferEndsWith(sql, delimiter))) { executeSQL(sql.substring(0, sql.length() - delimiter.length())); sql.replace(0, sql.length(), ""); } } // Catch any statements not followed by ; if (sql.length() > 0) { executeSQL(sql.toString()); } } catch (IOException e) { log.error("Error occurred while executing SQL script for creating registry database", e); throw new APIMigrationException( "Error occurred while executing SQL script for creating registry database", e); } finally { if (reader != null) { reader.close(); } } }
From source file:org.openbravo.advpaymentmngt.ad_actionbutton.ProcessInvoice.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { VariablesSecureApp vars = new VariablesSecureApp(request); if (vars.commandIn("DEFAULT")) { final String strWindowId = vars.getGlobalVariable("inpwindowId", "ProcessInvoice|Window_ID", IsIDFilter.instance);/* w w w . j a v a 2 s .c om*/ final String strTabId = vars.getGlobalVariable("inpTabId", "ProcessInvoice|Tab_ID", IsIDFilter.instance); final String strC_Invoice_ID = vars.getGlobalVariable("inpcInvoiceId", strWindowId + "|C_Invoice_ID", "", IsIDFilter.instance); final String strdocaction = vars.getStringParameter("inpdocaction"); final String strProcessing = vars.getStringParameter("inpprocessing", "Y"); final String strOrg = vars.getRequestGlobalVariable("inpadOrgId", "ProcessInvoice|Org_ID", IsIDFilter.instance); final String strClient = vars.getStringParameter("inpadClientId", IsIDFilter.instance); final String strdocstatus = vars.getRequiredStringParameter("inpdocstatus"); final String stradTableId = "318"; final int accesslevel = 1; if ((org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(this, vars.getRole(), strTabId)) || !(Utility.isElementInList( Utility.getContext(this, vars, "#User_Client", strWindowId, accesslevel), strClient) && Utility.isElementInList( Utility.getContext(this, vars, "#User_Org", strWindowId, accesslevel), strOrg))) { OBError myError = Utility.translateError(this, vars, vars.getLanguage(), Utility.messageBD(this, "NoWriteAccess", vars.getLanguage())); vars.setMessage(strTabId, myError); printPageClosePopUp(response, vars); } else { printPageDocAction(response, vars, strC_Invoice_ID, strdocaction, strProcessing, strdocstatus, stradTableId, strWindowId); } } else if (vars.commandIn("SAVE_BUTTONDocAction111")) { final String strWindowId = vars.getGlobalVariable("inpwindowId", "ProcessInvoice|Window_ID", IsIDFilter.instance); final String strTabId = vars.getGlobalVariable("inpTabId", "ProcessInvoice|Tab_ID", IsIDFilter.instance); final String strC_Invoice_ID = vars.getGlobalVariable("inpKey", strWindowId + "|C_Invoice_ID", ""); final String strdocaction = vars.getStringParameter("inpdocaction"); final String strVoidInvoiceDate = vars.getStringParameter("inpVoidedDocumentDate"); final String strVoidInvoiceAcctDate = vars.getStringParameter("inpVoidedDocumentAcctDate"); final String strOrg = vars.getGlobalVariable("inpadOrgId", "ProcessInvoice|Org_ID", IsIDFilter.instance); OBError myMessage = null; try { Invoice invoice = dao.getObject(Invoice.class, strC_Invoice_ID); invoice.setDocumentAction(strdocaction); OBDal.getInstance().save(invoice); OBDal.getInstance().flush(); OBError msg = null; for (ProcessInvoiceHook hook : hooks) { msg = hook.preProcess(invoice, strdocaction); if (msg != null && "Error".equals(msg.getType())) { vars.setMessage(strTabId, msg); String strWindowPath = Utility.getTabURL(strTabId, "R", true); if (strWindowPath.equals("")) strWindowPath = strDefaultServlet; printPageClosePopUp(response, vars, strWindowPath); return; } } // check BP currency if ("CO".equals(strdocaction)) { // check BP currency if (invoice.getBusinessPartner().getCurrency() == null) { String errorMSG = Utility.messageBD(this, "InitBPCurrencyLnk", vars.getLanguage(), false); msg = new OBError(); msg.setType("Error"); msg.setTitle(Utility.messageBD(this, "Error", vars.getLanguage())); msg.setMessage(String.format(errorMSG, invoice.getBusinessPartner().getId(), invoice.getBusinessPartner().getName())); vars.setMessage(strTabId, msg); printPageClosePopUp(response, vars, Utility.getTabURL(strTabId, "R", true)); return; } } OBContext.setAdminMode(true); Process process = null; try { process = dao.getObject(Process.class, "111"); } finally { OBContext.restorePreviousMode(); } Map<String, String> parameters = null; if (!strVoidInvoiceDate.isEmpty() && !strVoidInvoiceAcctDate.isEmpty()) { Date voidDate = null; Date voidAcctDate = null; try { voidDate = OBDateUtils.getDate(strVoidInvoiceDate); voidAcctDate = OBDateUtils.getDate(strVoidInvoiceAcctDate); } catch (ParseException pe) { voidDate = new Date(); voidAcctDate = new Date(); log4j.error("Not possible to parse the following date: " + strVoidInvoiceDate, pe); log4j.error("Not possible to parse the following date: " + strVoidInvoiceAcctDate, pe); } parameters = new HashMap<String, String>(); parameters.put("voidedDocumentDate", OBDateUtils.formatDate(voidDate, "yyyy-MM-dd")); parameters.put("voidedDocumentAcctDate", OBDateUtils.formatDate(voidAcctDate, "yyyy-MM-dd")); } final ProcessInstance pinstance = CallProcess.getInstance().call(process, strC_Invoice_ID, parameters); OBDal.getInstance().getSession().refresh(invoice); invoice.setAPRMProcessinvoice(invoice.getDocumentAction()); // Remove invoice's used credit description if ("RE".equals(strdocaction) && pinstance.getResult() != 0L) { final String invDesc = invoice.getDescription(); if (invDesc != null) { final String creditMsg = Utility.messageBD(this, "APRM_InvoiceDescUsedCredit", vars.getLanguage()); if (creditMsg != null) { final StringBuffer newDesc = new StringBuffer(); for (final String line : invDesc.split("\n")) { if (!line.startsWith(creditMsg.substring(0, creditMsg.lastIndexOf("%s")))) { newDesc.append(line); if (!"".equals(line)) newDesc.append("\n"); } } invoice.setDescription(newDesc.toString()); } } } OBDal.getInstance().save(invoice); OBDal.getInstance().flush(); OBContext.setAdminMode(); try { // on error close popup if (pinstance.getResult() == 0L) { OBDal.getInstance().commitAndClose(); final PInstanceProcessData[] pinstanceData = PInstanceProcessData.select(this, pinstance.getId()); myMessage = Utility.getProcessInstanceMessage(this, vars, pinstanceData); log4j.debug(myMessage.getMessage()); vars.setMessage(strTabId, myMessage); String strWindowPath = Utility.getTabURL(strTabId, "R", true); if (strWindowPath.equals("")) strWindowPath = strDefaultServlet; printPageClosePopUp(response, vars, strWindowPath); return; } } finally { OBContext.restorePreviousMode(); } for (ProcessInvoiceHook hook : hooks) { msg = hook.postProcess(invoice, strdocaction); if (msg != null && "Error".equals(msg.getType())) { vars.setMessage(strTabId, msg); String strWindowPath = Utility.getTabURL(strTabId, "R", true); if (strWindowPath.equals("")) strWindowPath = strDefaultServlet; printPageClosePopUp(response, vars, strWindowPath); OBDal.getInstance().rollbackAndClose(); return; } } OBDal.getInstance().commitAndClose(); final PInstanceProcessData[] pinstanceData = PInstanceProcessData.select(this, pinstance.getId()); myMessage = Utility.getProcessInstanceMessage(this, vars, pinstanceData); log4j.debug(myMessage.getMessage()); vars.setMessage(strTabId, myMessage); OBContext.setAdminMode(); try { if (!"CO".equals(strdocaction)) { String strWindowPath = Utility.getTabURL(strTabId, "R", true); if (strWindowPath.equals("")) strWindowPath = strDefaultServlet; printPageClosePopUp(response, vars, strWindowPath); return; } } finally { OBContext.restorePreviousMode(); } if ("CO".equals(strdocaction)) { // Need to refresh the invoice again from the db invoice = dao.getObject(Invoice.class, strC_Invoice_ID); OBContext.setAdminMode(false); String invoiceDocCategory = ""; try { invoiceDocCategory = invoice.getDocumentType().getDocumentCategory(); /* * Print a grid popup in case of credit payment */ // If the invoice grand total is ZERO or already has payments (due to // payment method automation) or the business partner does not have a default financial // account defined or invoice's payment method is not inside BP's financial // account do not cancel credit if (BigDecimal.ZERO.compareTo(invoice.getGrandTotalAmount()) != 0 && isPaymentMethodConfigured(invoice) && !isInvoiceWithPayments(invoice) && (AcctServer.DOCTYPE_ARInvoice.equals(invoiceDocCategory) || AcctServer.DOCTYPE_APInvoice.equals(invoiceDocCategory))) { creditPayments = dao.getCustomerPaymentsWithCredit(invoice.getOrganization(), invoice.getBusinessPartner(), invoice.isSalesTransaction()); if (creditPayments != null && !creditPayments.isEmpty()) { printPageCreditPaymentGrid(response, vars, strC_Invoice_ID, strdocaction, strTabId, strC_Invoice_ID, strdocaction, strWindowId, strTabId, invoice.getInvoiceDate(), strOrg); } } } finally { OBContext.restorePreviousMode(); } executePayments(response, vars, strWindowId, strTabId, strC_Invoice_ID, strOrg); } } catch (ServletException ex) { myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage()); if (!myMessage.isConnectionAvailable()) { bdErrorConnection(response); return; } else vars.setMessage(strTabId, myMessage); } } else if (vars.commandIn("GRIDLIST")) { final String strWindowId = vars.getGlobalVariable("inpwindowId", "ProcessInvoice|Window_ID", IsIDFilter.instance); final String strC_Invoice_ID = vars.getGlobalVariable("inpKey", strWindowId + "|C_Invoice_ID", "", IsIDFilter.instance); printGrid(response, vars, strC_Invoice_ID); } else if (vars.commandIn("USECREDITPAYMENTS") || vars.commandIn("CANCEL_USECREDITPAYMENTS")) { final String strWindowId = vars.getGlobalVariable("inpwindowId", "ProcessInvoice|Window_ID", IsIDFilter.instance); final String strTabId = vars.getGlobalVariable("inpTabId", "ProcessInvoice|Tab_ID", IsIDFilter.instance); final String strC_Invoice_ID = vars.getGlobalVariable("inpKey", strWindowId + "|C_Invoice_ID", ""); final String strPaymentDate = vars.getRequiredStringParameter("inpPaymentDate"); final String strOrg = vars.getGlobalVariable("inpadOrgId", "ProcessInvoice|Org_ID", IsIDFilter.instance); final String strCreditPaymentIds; if (vars.commandIn("CANCEL_USECREDITPAYMENTS")) { strCreditPaymentIds = null; } else { strCreditPaymentIds = vars.getInParameter("inpCreditPaymentId", IsIDFilter.instance); } /* * Use credit logic */ if (strCreditPaymentIds != null && !strCreditPaymentIds.isEmpty()) { List<FIN_Payment> selectedCreditPayment = FIN_Utility.getOBObjectList(FIN_Payment.class, strCreditPaymentIds); HashMap<String, BigDecimal> selectedCreditPaymentAmounts = FIN_AddPayment .getSelectedBaseOBObjectAmount(vars, selectedCreditPayment, "inpPaymentAmount"); try { OBContext.setAdminMode(true); final Invoice invoice = OBDal.getInstance().get(Invoice.class, strC_Invoice_ID); final StringBuffer creditPaymentsIdentifiers = new StringBuffer(); BigDecimal totalUsedCreditAmt = BigDecimal.ZERO; for (final FIN_Payment creditPayment : selectedCreditPayment) { final BigDecimal usedCreditAmt = selectedCreditPaymentAmounts.get(creditPayment.getId()); // Set Used Credit = Amount + Previous used credit introduced by the user creditPayment.setUsedCredit(usedCreditAmt.add(creditPayment.getUsedCredit())); final StringBuffer description = new StringBuffer(); if (creditPayment.getDescription() != null && !creditPayment.getDescription().equals("")) description.append(creditPayment.getDescription()).append("\n"); description.append(String.format( Utility.messageBD(this, "APRM_CreditUsedinInvoice", vars.getLanguage()), invoice.getDocumentNo())); String truncateDescription = (description.length() > 255) ? description.substring(0, 251).concat("...").toString() : description.toString(); creditPayment.setDescription(truncateDescription); totalUsedCreditAmt = totalUsedCreditAmt.add(usedCreditAmt); creditPaymentsIdentifiers.append(creditPayment.getDocumentNo()); creditPaymentsIdentifiers.append(", "); } creditPaymentsIdentifiers.delete(creditPaymentsIdentifiers.length() - 2, creditPaymentsIdentifiers.length()); creditPaymentsIdentifiers.append("\n"); final List<FIN_PaymentScheduleDetail> paymentScheduleDetails = new ArrayList<FIN_PaymentScheduleDetail>(); final HashMap<String, BigDecimal> paymentScheduleDetailsAmounts = new HashMap<String, BigDecimal>(); BigDecimal allocatedAmt = BigDecimal.ZERO; for (final FIN_PaymentScheduleDetail paymentScheduleDetail : dao .getInvoicePendingScheduledPaymentDetails(invoice)) { if (totalUsedCreditAmt.compareTo(allocatedAmt) > 0) { final BigDecimal pendingToAllocate = totalUsedCreditAmt.subtract(allocatedAmt); paymentScheduleDetails.add(paymentScheduleDetail); final BigDecimal psdAmt = paymentScheduleDetail.getAmount(); if (psdAmt.compareTo(pendingToAllocate) <= 0) { paymentScheduleDetailsAmounts.put(paymentScheduleDetail.getId(), psdAmt); allocatedAmt = allocatedAmt.add(psdAmt); } else { paymentScheduleDetailsAmounts.put(paymentScheduleDetail.getId(), pendingToAllocate); allocatedAmt = allocatedAmt.add(pendingToAllocate); } } } // Create new Payment final boolean isSalesTransaction = invoice.isSalesTransaction(); final DocumentType docType = FIN_Utility.getDocumentType(invoice.getOrganization(), isSalesTransaction ? AcctServer.DOCTYPE_ARReceipt : AcctServer.DOCTYPE_APPayment); final String strPaymentDocumentNo = FIN_Utility.getDocumentNo(docType, docType.getTable() != null ? docType.getTable().getDBTableName() : ""); final FIN_FinancialAccount bpFinAccount = isSalesTransaction ? invoice.getBusinessPartner().getAccount() : invoice.getBusinessPartner().getPOFinancialAccount(); // Calculate Conversion Rate final ConversionRate conversionRate = StringUtils.equals(invoice.getCurrency().getId(), bpFinAccount.getCurrency().getId()) ? null : FinancialUtils.getConversionRate(FIN_Utility.getDate(strPaymentDate), invoice.getCurrency(), bpFinAccount.getCurrency(), invoice.getOrganization(), invoice.getClient()); final FIN_Payment newPayment = FIN_AddPayment.savePayment(null, isSalesTransaction, docType, strPaymentDocumentNo, invoice.getBusinessPartner(), invoice.getPaymentMethod(), bpFinAccount, "0", FIN_Utility.getDate(strPaymentDate), invoice.getOrganization(), invoice.getDocumentNo(), paymentScheduleDetails, paymentScheduleDetailsAmounts, false, false, invoice.getCurrency(), conversionRate != null ? conversionRate.getMultipleRateBy() : null, null); newPayment.setAmount(BigDecimal.ZERO); newPayment.setGeneratedCredit(BigDecimal.ZERO); newPayment.setUsedCredit(totalUsedCreditAmt); // Link new Payment with the credit payments used for (final FIN_Payment creditPayment : selectedCreditPayment) { final BigDecimal usedCreditAmt = selectedCreditPaymentAmounts.get(creditPayment.getId()); FIN_PaymentProcess.linkCreditPayment(newPayment, usedCreditAmt, creditPayment); } // Process the new payment OBError message = FIN_AddPayment.processPayment(vars, this, "P", newPayment); if ("Success".equals(message.getType())) { // Update Invoice's description final StringBuffer invDesc = new StringBuffer(); if (invoice.getDescription() != null) { invDesc.append(invoice.getDescription()); invDesc.append("\n"); } invDesc.append(String.format( Utility.messageBD(this, "APRM_InvoiceDescUsedCredit", vars.getLanguage()), creditPaymentsIdentifiers.toString())); invoice.setDescription(invDesc.toString()); } else { message.setMessage(OBMessageUtils.messageBD("PaymentError") + " " + message.getMessage()); vars.setMessage(strTabId, message); } } catch (final Exception e) { log4j.error("Exception while canceling the credit in the invoice: " + strC_Invoice_ID); e.printStackTrace(); } finally { OBContext.restorePreviousMode(); } } executePayments(response, vars, strWindowId, strTabId, strC_Invoice_ID, strOrg); } }