List of usage examples for java.lang StringBuffer delete
@Override public synchronized StringBuffer delete(int start, int end)
From source file:org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl.java
/** * This method is called by performLookup method to generate action urls. * It calls the method getCustomActionUrls to get html data, calls getMaintenanceUrl to get the actual html tag, * and returns a formatted/concatenated string of action urls. * * @see LookupableHelperService#getActionUrls(org.kuali.rice.krad.bo.BusinessObject) *//* w ww. j a v a 2 s .c o m*/ final public String getActionUrls(BusinessObject businessObject, List pkNames, BusinessObjectRestrictions businessObjectRestrictions) { StringBuffer actions = new StringBuffer(); List<HtmlData> htmlDataList = getCustomActionUrls(businessObject, pkNames); for (HtmlData htmlData : htmlDataList) { actions.append(getMaintenanceUrl(businessObject, htmlData, pkNames, businessObjectRestrictions)); if (htmlData.getChildUrlDataList() != null) { if (htmlData.getChildUrlDataList().size() > 0) { actions.append(ACTION_URLS_CHILDREN_STARTER); for (HtmlData childURLData : htmlData.getChildUrlDataList()) { actions.append(getMaintenanceUrl(businessObject, childURLData, pkNames, businessObjectRestrictions)); actions.append(ACTION_URLS_CHILDREN_SEPARATOR); } if (actions.toString().endsWith(ACTION_URLS_CHILDREN_SEPARATOR)) actions.delete(actions.length() - ACTION_URLS_CHILDREN_SEPARATOR.length(), actions.length()); actions.append(ACTION_URLS_CHILDREN_END); } } actions.append(ACTION_URLS_SEPARATOR); } if (actions.toString().endsWith(ACTION_URLS_SEPARATOR)) actions.delete(actions.length() - ACTION_URLS_SEPARATOR.length(), actions.length()); return actions.toString(); }
From source file:org.agnitas.dao.impl.ImportRecipientsDaoImpl.java
@Override public HashMap<ProfileRecipientFields, ValidatorResults> getDuplicateRecipientsFromExistData( Map<ProfileRecipientFields, ValidatorResults> listOfValidBeans, ImportProfile profile, CSVColumnState[] columns) {/*from w w w .j a v a 2 s. co m*/ final HashMap<ProfileRecipientFields, ValidatorResults> result = new HashMap<ProfileRecipientFields, ValidatorResults>(); if (listOfValidBeans.isEmpty()) { return result; } final HashMap<ImportKeyColumnsKey, ProfileRecipientFields> columnKeyValueToTemporaryIdMap = new HashMap<ImportKeyColumnsKey, ProfileRecipientFields>(); final JdbcTemplate template = createJdbcTemplate(); List parameters = new ArrayList(); Map<String, List<Object>> parametersMap = new HashMap<String, List<Object>>(); String columnKeyBuffer = "("; for (ProfileRecipientFields profileRecipientFields : listOfValidBeans.keySet()) { ImportKeyColumnsKey keyValue = ImportKeyColumnsKey.createInstance(profile, profileRecipientFields, columns); if (columnKeyValueToTemporaryIdMap.containsKey(keyValue)) { result.put(profileRecipientFields, null); continue; } columnKeyBuffer += keyValue.getParametersString(); keyValue.addParameters(parametersMap); columnKeyValueToTemporaryIdMap.put(keyValue, profileRecipientFields); } columnKeyBuffer = columnKeyBuffer.substring(0, columnKeyBuffer.length() - 1); columnKeyBuffer = columnKeyBuffer + ")"; ImportKeyColumnsKey keyColumnsKey = columnKeyValueToTemporaryIdMap.keySet().iterator().next(); Iterator<String> keyColumnIterator = keyColumnsKey.getKeyColumnsMap().keySet().iterator(); StringBuffer sqlQuery = new StringBuffer("SELECT customer_id, "); StringBuffer wherePart = new StringBuffer(""); Map<String, Integer> columnTypes = new HashMap<String, Integer>(); while (keyColumnIterator.hasNext()) { String keyColumnName = keyColumnIterator.next(); CSVColumnState columnState = keyColumnsKey.getKeyColumnsMap().get(keyColumnName); String column = keyColumnName; String columnAlias = ImportKeyColumnsKey.KEY_COLUMN_PREFIX + keyColumnName; sqlQuery.append(column + " AS " + columnAlias + ","); int type = columnState.getType(); if (AgnUtils.isOracleDB() && (keyColumnName.equals("email") || type == CSVColumnState.TYPE_NUMERIC || type == CSVColumnState.TYPE_DATE)) { wherePart.append(column); } else { wherePart.append("LOWER(" + column + ")"); } wherePart.append(" IN " + columnKeyBuffer + " AND "); // gather parameters List<Object> objectList = parametersMap.get(keyColumnName); if (objectList != null) { parameters.addAll(objectList); } columnTypes.put(columnAlias, type); } sqlQuery.delete(sqlQuery.length() - 1, sqlQuery.length()); wherePart.delete(wherePart.length() - 4, wherePart.length()); sqlQuery.append(" FROM customer_" + profile.getCompanyId() + "_tbl c WHERE ("); sqlQuery.append(wherePart); sqlQuery.append(")"); final List<Map> resultList = template.queryForList(sqlQuery.toString(), parameters.toArray()); for (Map row : resultList) { ImportKeyColumnsKey columnsKey = ImportKeyColumnsKey.createInstance(row); ProfileRecipientFields recipientFields = columnKeyValueToTemporaryIdMap.get(columnsKey); if (recipientFields != null) { result.put(recipientFields, null); if (profile.getUpdateAllDuplicates() || (recipientFields.getUpdatedIds() == null || recipientFields.getUpdatedIds().size() == 0)) { recipientFields.addUpdatedIds(((Number) row.get("customer_id")).intValue()); } } } return result; }
From source file:org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.java
private String editLine(String textinLine, String tenantName) { // Format of the line will be <IP>=<IPvalue>,<Path>=<PathValue>.. StringBuffer outputBuffer = new StringBuffer(); Map<String, String> paramMap = new HashMap<String, String>(); String[] params = textinLine.split(AutoscalerConstant.ENTRY_SEPARATOR); for (int i = 0; i < params.length; i++) { // split the params one by one String param = params[i]; String[] values = param.split(AutoscalerConstant.VALUE_SEPARATOR); if (values.length != 2) { throw new AutoscalerServiceException("Incorrect format in parameters file"); }//from www. jav a2 s .c om String key = values[0]; String value = values[1]; String updatedValue = value; if (AutoscalerConstant.TENANT_KEY.equals(key)) { updatedValue = tenantName; } else if (AutoscalerConstant.APP_PATH_KEY.equals(key)) { updatedValue = getAppPathForTenant(tenantName, value); } paramMap.put(key, updatedValue); } // Loop through the map and put values into a string reOrganizeContent(outputBuffer, paramMap); // cleanup output buffer if (outputBuffer.substring(0, 1).equals(AutoscalerConstant.ENTRY_SEPARATOR)) { outputBuffer.delete(0, 1); } return outputBuffer.toString(); }
From source file:cc.siara.csv_ml_demo.MainActivity.java
/** * Evaluates given XPath from Input box against Document generated by * parsing csv_ml in input box and sets value or node list to output box. *//*from ww w .j ava 2s . c o m*/ void processXPath() { EditText etInput = (EditText) findViewById(R.id.etInput); EditText etXPath = (EditText) findViewById(R.id.etXPath); CheckBox cbPretty = (CheckBox) findViewById(R.id.cbPretty); XPath xpath = XPathFactory.newInstance().newXPath(); MultiLevelCSVParser parser = new MultiLevelCSVParser(); Document doc = null; try { doc = parser.parseToDOM(new StringReader(etInput.getText().toString()), false); } catch (IOException e1) { e1.printStackTrace(); } if (doc == null) return; StringBuffer out_str = new StringBuffer(); try { XPathExpression expr = xpath.compile(etXPath.getText().toString()); try { Document outDoc = Util.parseXMLToDOM("<output></output>"); Element rootElement = outDoc.getDocumentElement(); NodeList ret = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < ret.getLength(); i++) { Object o = ret.item(i); if (o instanceof String) { out_str.append(o); } else if (o instanceof Node) { Node n = (Node) o; short nt = n.getNodeType(); switch (nt) { case Node.TEXT_NODE: case Node.ATTRIBUTE_NODE: case Node.CDATA_SECTION_NODE: // Only one value gets // evaluated? if (out_str.length() > 0) out_str.append(','); if (nt == Node.ATTRIBUTE_NODE) out_str.append(n.getNodeValue()); else out_str.append(n.getTextContent()); break; case Node.ELEMENT_NODE: rootElement.appendChild(outDoc.importNode(n, true)); break; } } } if (out_str.length() > 0) { rootElement.setTextContent(out_str.toString()); out_str.setLength(0); } out_str.append(Util.docToString(outDoc, true)); } catch (Exception e) { // Thrown most likely because the given XPath evaluates to a // string out_str.append(expr.evaluate(doc)); } } catch (XPathExpressionException e) { e.printStackTrace(); } if (out_str.length() > 5 && out_str.substring(0, 5).equals("<?xml")) out_str.delete(0, out_str.indexOf(">") + 1); EditText etOutput = (EditText) findViewById(R.id.etOutput); etOutput.setText(out_str.toString()); // tfOutputSize.setText(String.valueOf(xmlString.length())); }
From source file:org.egov.works.web.actions.reports.WorkProgressRegisterAction.java
public HashMap<String, Object> getQueryForWorkProgressRegister() { final StringBuffer query = new StringBuffer(500); final ArrayList<Object> paramList = new ArrayList<Object>(); final HashMap<String, Object> queryMap = new HashMap<String, Object>(); final StringBuilder srchCrit = new StringBuilder(3000); final StringBuffer orderQry = new StringBuffer(100); srchCrit.append("Report"); query.append(//from w ww . j a v a 2 s . c o m "from org.egov.works.models.workorder.WorkOrderEstimate as woe left outer join woe.milestone milestone left outer join milestone.trackMilestone trackMilestone "); query.append("where woe.workOrder.parent is null and woe.workOrder.egwStatus.code='APPROVED' "); query.append("and milestone.egwStatus.code='APPROVED' and trackMilestone.egwStatus.code='APPROVED' "); if (sourcePage == null || StringUtils.isEmpty(sourcePage)) { if (!workOrderStatus.equalsIgnoreCase("-1")) { srchCrit.append(" for Work Order Status " + workOrderStatus); if (workOrderStatus.equalsIgnoreCase("APPROVED")) { query.append(" and woe.workOrder.egwStatus.code=?"); query.append( " and woe.workOrder.id not in (select objectId from org.egov.works.models.tender.OfflineStatus where objectType=?)"); paramList.add(workOrderStatus); paramList.add(WorkOrder.class.getSimpleName()); } else { query.delete(0, query.length() - 1); query.append( "from org.egov.works.models.workorder.WorkOrderEstimate as woe left outer join woe.milestone milestone left outer join milestone.trackMilestone trackMilestone,org.egov.works.models.tender.OfflineStatus st"); query.append( " where st.objectId=woe.workOrder.id and st.id=(select max(id) from org.egov.works.models.tender.OfflineStatus where objectId=woe.workOrder.id and objectType=?) and st.objectType=? and st.egwStatus.code=?"); query.append(" and woe.workOrder.parent is null and woe.workOrder.egwStatus.code='APPROVED' "); query.append( " and milestone.egwStatus.code='APPROVED' and trackMilestone.egwStatus.code='APPROVED' "); paramList.add(WorkOrder.class.getSimpleName()); paramList.add(WorkOrder.class.getSimpleName()); paramList.add(workOrderStatus); } } if (execDept != -1) { final Department dept = departmentService.getDepartmentById(execDept); srchCrit.append(" in " + dept.getName() + " Department "); query.append(" and woe.estimate.executingDepartment.id=?"); paramList.add(execDept); } if (fromDate != null && toDate == null && getFieldErrors().isEmpty()) { srchCrit.append(" from " + DateUtils.getFormattedDate(fromDate, dateFormat) + " to current date "); query.append(" and woe.workOrder.workOrderDate >= ? "); paramList.add(fromDate); } if (fromDate == null && toDate != null && getFieldErrors().isEmpty()) { srchCrit.append(" as on " + DateUtils.getFormattedDate(toDate, dateFormat)); query.append(" and woe.workOrder.workOrderDate <= ? "); paramList.add(toDate); } if (fromDate != null && toDate != null && getFieldErrors().isEmpty()) { srchCrit.append(" for date range " + DateUtils.getFormattedDate(fromDate, dateFormat) + " - " + DateUtils.getFormattedDate(toDate, dateFormat)); query.append(" and woe.workOrder.workOrderDate between ? and ? "); paramList.add(fromDate); paramList.add(toDate); } if (contractorId != null) { final Contractor contractor = (Contractor) getPersistenceService() .find("from Contractor where id=?", contractorId); srchCrit.append(" for Contractor " + contractor.getCode() + "-" + contractor.getName()); query.append("and woe.workOrder.contractor.id=? "); paramList.add(contractorId); } if (expenditureType != -1) { final NatureOfWork wtype = (NatureOfWork) getPersistenceService() .find("from NatureOfWork where id=?", expenditureType); srchCrit.append(" with Nature of Work " + wtype.getName()); query.append(" and woe.estimate.type.id=?"); paramList.add(expenditureType); } if (fund != -1) { final Fund f = (Fund) getPersistenceService().find("from Fund where id=?", fund); srchCrit.append(" under Fund " + f.getName()); query.append(" and woe.estimate.financialDetails[0].fund.id=?"); paramList.add(fund); } if (function != -1) { final CFunction fun = (CFunction) getPersistenceService().find("from CFunction where id=?", function); srchCrit.append(" for Function " + fun.getName()); query.append(" and woe.estimate.financialDetails[0].function.id=?"); paramList.add(function); } if (parentCategory != -1) { final EgwTypeOfWork tow = (EgwTypeOfWork) getPersistenceService() .find("from EgwTypeOfWork etw where etw.parentid is null and id=?", parentCategory); srchCrit.append(" with Type of Work " + tow.getDescription()); query.append(" and woe.estimate.parentCategory.id=?"); paramList.add(parentCategory); } if (category != -1) { final EgwTypeOfWork subtow = (EgwTypeOfWork) getPersistenceService() .find("from EgwTypeOfWork etw where id=? and parentid.id=?", category, parentCategory); srchCrit.append(" and Subtype of Work " + subtow.getDescription()); query.append(" and woe.estimate.category.id=?"); paramList.add(category); } if (preparedBy != -1) { final PersonalInformation prepBy = (PersonalInformation) getPersistenceService() .find("from PersonalInformation where id=?", preparedBy); srchCrit.append(" as Prepared by " + prepBy.getEmployeeName()); query.append(" and woe.workOrder.workOrderPreparedBy.idPersonalInformation=?"); paramList.add(preparedBy); } if (getScheme() != null && getScheme() != -1) { final Scheme sch = (Scheme) getPersistenceService().find("from Scheme where isactive=true and id=?", getScheme()); srchCrit.append(" under Scheme " + sch.getName()); query.append(" and woe.estimate.financialDetails[0].scheme.id=?"); paramList.add(getScheme()); } if (getSubScheme() != null && getSubScheme() != -1) { final SubScheme subsch = (SubScheme) getPersistenceService().find("from SubScheme where id=?", getSubScheme()); srchCrit.append(" and Subscheme " + subsch.getName()); query.append(" and woe.estimate.financialDetails[0].subScheme.id=?"); paramList.add(getSubScheme()); } if (budgetHead != -1) { final BudgetGroup bh = (BudgetGroup) getPersistenceService().find("from BudgetGroup where id=?", budgetHead); srchCrit.append(" with Budget Head " + bh.getName()); query.append(" and woe.estimate.financialDetails[0].budgetGroup.id=?"); paramList.add(budgetHead); } if (wardId != null) { final Boundary wardObj = boundaryService.getBoundaryById(wardId); srchCrit.append(" under Jurisdiction " + wardObj.getName()); query.append(" and woe.estimate.ward.id = ? "); paramList.add(wardId); } if (!milestoneStatus.equalsIgnoreCase("-1")) { srchCrit.append(" with Milestone Status " + milestoneStatus); query.append(" and trackMilestone.total " + milestoneStatuses.get(milestoneStatus)); query.append(" and trackMilestone.egwStatus.code=? "); paramList.add("APPROVED"); } if (engineerIncharge != null && engineerIncharge != -1) { final PersonalInformation engInc1 = (PersonalInformation) getPersistenceService() .find("from PersonalInformation where id=?", engineerIncharge); srchCrit.append(" for Work Order Assigned to User1 " + engInc1.getEmployeeName()); query.append(" and woe.workOrder.engineerIncharge.idPersonalInformation=?"); paramList.add(engineerIncharge); } if (engineerIncharge2 != null && engineerIncharge2 != -1) { final PersonalInformation engInc2 = (PersonalInformation) getPersistenceService() .find("from PersonalInformation where id=?", engineerIncharge2); srchCrit.append(" for Work Order Assigned to User2 " + engInc2.getEmployeeName()); query.append(" and woe.workOrder.engineerIncharge2.idPersonalInformation=?"); paramList.add(engineerIncharge2); } searchCriteria = srchCrit.toString(); } if (sourcePage != null && (sourcePage.equalsIgnoreCase("deptWiseReport") || sourcePage.equalsIgnoreCase("deptWiseReportForWP"))) { if (woId != null) { query.append(" and woe.workOrder.id=?"); paramList.add(Long.valueOf(woId.toString())); } if (estId != null) { query.append(" and woe.estimate.id=?"); paramList.add(Long.valueOf(estId.toString())); } } orderQry.append(" order by woe.id desc "); final String countQuery = "select count(distinct woe.id) " + query.toString(); final String finalQuery = "select woe " + query.append(orderQry).toString(); queryMap.put("countQuery", countQuery); queryMap.put("finalQuery", finalQuery); queryMap.put("params", paramList); return queryMap; }
From source file:edu.ncsa.sstde.indexing.postgis.PostgisIndexer.java
private void asSql(MatchedIndexedGraph graph, SqlQueryBuilder builder, BindingSet sparqlBindings) { StringBuffer from = new StringBuffer(SELECT); Map<String, String> verseNameMappings = graph.getVerseNameMappings(); for (String varName : graph.getUsedVarNames()) { String name = verseNameMappings.get(varName); if (name != null) { from.append(' ').append(name).append(','); }//from ww w . ja va2 s . c o m } if (from.length() == SELECT.length()) { for (String varName : verseNameMappings.values()) { from.append(' ').append(varName).append(','); } } // for (String column : graph.getNameMappings().keySet()) { // from.append(' ').append(column).append(','); // } Map<String, String> verseMapping = verseNameMappings; from.deleteCharAt(from.length() - 1); from.append(FROM); from.append(this.getName()); // compose the where clause StringBuffer where = new StringBuffer(); for (FunctionCall call : graph.getFunctionCalls()) { URIImpl url = new URIImpl(call.getURI()); where.append(ST_PREFIX).append(url.getLocalName()).append('('); for (int i = 0; i < call.getArgs().size(); i++) { ValueExpr param = call.getArgs().get(i); if (param instanceof Var) { where.append(verseMapping.get(((Var) param).getName())).append(','); } else if (param instanceof ValueConstant) { where.append('?').append(','); builder.inputBindings.add( new Binding(Types.OTHER, parseLiteral((Literal) ((ValueConstant) param).getValue()))); } } where.deleteCharAt(where.length() - 1).append(")=true").append(AND); } for (Compare compare : graph.getCompares()) { addCompareWhere(where, compare, builder, verseMapping); where.append(AND); } for (VarFilter filter : graph.getVarFilters()) { where.append(filter.getVarName()).append("=?").append(AND); builder.inputBindings.add(new Binding(Types.VARCHAR, filter.getValue())); // System.out.println(filter); } for (@SuppressWarnings("unused") Regex regex : graph.getRegexs()) { } if (where.length() > 0) { where.delete(where.length() - 5, where.length() - 1); } // compose the order by clause StringBuffer orderby = new StringBuffer(); if (graph.getOrders() != null && graph.getOrders() instanceof List) { List<OrderElem> orders = (List<OrderElem>) graph.getOrders(); Map<String, LiteralDef> literalDefMap = this.getSettings().getIndexGraph().getLiteralDefMap(); for (int i = graph.getOrders().size() - 1; i > -1; i--) { OrderElem order = orders.get(i); if (order.getExpr() instanceof Var) { String colName = verseMapping.get(((Var) order.getExpr()).getName()); if (literalDefMap.get(colName) != null) { orderby.append(colName); orderby.append(order.isAscending() ? ASC : DESC); orderby.append(','); } } } } // for (OrderElem order : graph.getOrders()) { // if (order.getExpr() instanceof Var) { // orderby.append(verseMapping.get(((Var) order.getExpr()) // .getName())); // orderby.append(order.isAscending() ? ASC : DESC); // orderby.append(','); // } // // } if (orderby.length() > 0) { orderby.deleteCharAt(orderby.length() - 1); } // combine all the query segments if (where.length() > 0) { from.append(WHERE).append(where); } if (orderby.length() > 0) { from.append(ORDER_BY).append(orderby); } builder.setSQL(from.toString()); builder.setLimit(graph.getLimit()); }
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);/*from ww w. ja v a2s. c o m*/ 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); } }
From source file:com.mysql.stresstool.RunnableQueryInsertPCH.java
@Override public boolean createSchema(StressTool sTool) { // Custom schema creation this is the default for the stresstool but can be anything String DropTables1 = "Drop table IF EXISTS tbtest"; String DropTables2 = "Drop table IF EXISTS tbtest_child"; String TruncateTables1 = "Truncate table tbtest"; String TruncateTables2 = "Truncate table tbtest_child"; Connection conn = null;/* w w w. j av a2 s . c o m*/ Statement stmt = null; try { if (jdbcUrlMap.get("dbType") != null && !((String) jdbcUrlMap.get("dbType")).equals("MySQL")) { conn = DriverManager.getConnection((String) jdbcUrlMap.get("dbType"), "test", "test"); } else conn = DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl")); conn.setAutoCommit(false); stmt = conn.createStatement(); StringBuffer sb = new StringBuffer(); for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) { sb.append("CREATE TABLE IF NOT EXISTS tbtest" + iTable + "("); if (this.isUseAutoIncrement()) { sb.append("`autoInc` bigint(11) AUTO_INCREMENT NOT NULL,"); } sb.append(" `a` int(11) NOT NULL,"); sb.append(" `uuid` char(36) NOT NULL,"); sb.append(" `serverid` int NOT NULL,"); sb.append(" `b` varchar(100) NOT NULL,"); sb.append(" `c` char(200) NOT NULL,"); sb.append(" `counter` bigint(20) NULL, "); sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,"); sb.append(" `partitionid` int NOT NULL DEFAULT 0,"); sb.append(" `strrecordtype` char(3) NULL"); if (this.isUseAutoIncrement()) { sb.append(", PRIMARY KEY (`autoInc`), INDEX `IDX_a` (a), INDEX `IDX_uuid` (uuid) "); } else { if (!this.doSimplePk) sb.append(", PRIMARY KEY (`uuid`), INDEX `IDX_a` (a), INDEX `serverid` (serverid) "); else sb.append(", PRIMARY KEY (`a`), INDEX `IDX_uuid` (uuid), INDEX `serverid` (serverid) "); } sb.append(") ENGINE=" + sTool.tableEngine); if (!sb.toString().equals("")) stmt.addBatch(sb.toString()); sb.delete(0, sb.length()); } String tbts1 = sb.toString(); sb = new StringBuffer(); for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) { sb.append("CREATE TABLE IF NOT EXISTS tbtest_child" + iTable); sb.append("(`a` int(11) NOT NULL,"); sb.append(" `serverid` int NOT NULL,"); sb.append("`bb` int(11) AUTO_INCREMENT NOT NULL,"); sb.append(" `partitionid` int NOT NULL DEFAULT 0,"); if (operationShort) sb.append(" `stroperation` VARCHAR(254) NULL,"); else sb.append(" `stroperation` TEXT(41845) NULL,"); sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"); sb.append(", PRIMARY KEY (`a`,`bb`), UNIQUE(`bb`), INDEX `serverid` (serverid)"); sb.append(") ENGINE=" + sTool.tableEngine); if (!sb.toString().equals("")) stmt.addBatch(sb.toString()); sb.delete(0, sb.length()); } String tbts2 = sb.toString(); System.out.println(tbts1); if (!doSimplePk) System.out.println(tbts2); if (sTool.droptable) { System.out.println( "****============================================================================*******"); for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) { System.out.println( "**** Please wait DROP table tbtest" + iTable + " it could take a LOT of time *******"); stmt.execute(DropTables1 + iTable); stmt.execute("COMMIT"); } if (!doSimplePk) { for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) { System.out.println("**** Please wait DROP table tbtest_child" + iTable + " it could take a LOT of time *******"); stmt.execute(DropTables2 + iTable); stmt.execute("COMMIT"); } } stmt.execute("COMMIT"); System.out.println("**** DROP finished *******"); System.out.println( "****============================================================================*******"); } if (sTool.createtable) stmt.executeBatch(); if (sTool.truncate) { System.out.println( "****============================================================================*******"); for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) { System.out.println("**** Please wait TRUNCATE table tbtest" + iTable + " it could take a LOT of time *******"); stmt.execute(TruncateTables1 + iTable); } if (!doSimplePk) { for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) { System.out.println("**** Please wait TRUNCATE table tbtest_child" + iTable + " it could take a LOT of time *******"); stmt.execute(TruncateTables2 + iTable); } } System.out.println("**** TRUNCATE finish *******"); System.out.println( "****============================================================================*******"); } } catch (Exception ex) { ex.printStackTrace( ); return false; } finally { try { conn.close(); return true; } catch (SQLException ex1) { ex1.printStackTrace(); return false; } } }
From source file:Leitura.Ecobertura.java
public void escreveTxt() throws IOException { //mtodo para pegar os nomes dos mtodos declarados String auxLinha = null;//from w ww. j a va2 s.co m char aux[] = null; StringBuffer sbClasse = new StringBuffer(); StringBuffer sbLinha = new StringBuffer(); StringBuffer sbMetodo = new StringBuffer(); String metodoTemp; boolean controleClasse = false; // Pega somente os elementos com tag "tr" Elements elements = document.getElementsByTag("tr"); for (Element children : elements) { if (StringUtils.isBlank(children.text())) { continue; } children.getElementsByClass("comment").remove(); // System.out.println(children.text()); //----------------- Dispensa Comentrios ----------------- //auxLinha = children.getElementsByTag("span").eq(0).text(); /*if (auxLinha.contains("/*")) { comentario = true; } else if(auxLinha.contains("//")){ comentario = true; controle = true; // controla comentrio com // } if (auxLinha.contains("*//*")) { comentario = false; }else if(auxLinha.contains("\n") && controle == true){ comentario = false; controle = false; }*/ //------------------ Fim dispensa comentrios -------------- // if (comentario == false) { //--------------------- verifica as linhas do cdigo ------------------- if (StringUtils.isNotBlank(children.getElementsByClass("numLine").text())) { aux = children.getElementsByClass("numLine").text().toCharArray(); for (int i = 0; i < aux.length; i++) { //System.out.println("["+aux[i]+"]"); if (aux[i] >= 48 && aux[i] <= 57) { // pega o nmero da linha sbLinha.append(aux[i]); } } auxLinha = sbLinha.toString(); if (StringUtils.isNotBlank(auxLinha)) { // transforma a linha para inteiro qtdeLinhas = Integer.parseInt(auxLinha); } sbLinha.delete(0, sbLinha.length()); } // ------------------- Fim linhas --------------------------------- Elements pre = children.getElementsByTag("pre"); for (Element element : pre) { String tagMetodo = element.getElementsByTag("span").eq(0).text(); //------------------------- Verifica classe ------------------------- if (element.getElementsByTag("span").text().contains("class")) { element.select("span.keyword").remove(); if (controleClasse == false) { classe = element.text().trim(); aux = classe.toCharArray(); for (int j = 0; j < aux.length; j++) { if ((65 <= aux[j]) && (aux[j] <= 90) || (aux[j] >= 97) && (aux[j] <= 122) || (aux[j] == 95)) { sbClasse.append(aux[j]); //System.out.println(j + ", " + sbClasse); if (j < aux.length - 1) { // System.out.println("size: "+aux.length+" j: "+j); if ((aux[j + 1] == ' ') || (aux[j + 1] == '{') || (aux[j + 1] == '<')) { // System.out.println("entrei"); if ((j + 1) < aux.length - 1) { for (int k = j++; k < aux.length; k++) { aux[k] = ' '; } } } } } } excluiLinhas.add(qtdeLinhas); classe = sbClasse.toString().replaceAll("\r", "").replaceAll("\t", "").replaceAll("\n", ""); controleClasse = true; } // System.out.println("Classe: " + classe); } //------------------------------- Fim verifica classe------------------------------ //------------------------------ Verifica mtodo ---------------------------------- //else if (tagMetodo.equals("privtate") || tagMetodo.equals("public") || tagMetodo.equals("protected")) { else if (element.getElementsByTag("span").text().contains("privtate") || element.getElementsByTag("span").text().contains("public") || element.getElementsByTag("span").text().contains("protected") || element.getElementsByTag("span").text().contains("static") || element.getElementsByTag("span").text().contains("final") || element.getElementsByTag("span").text().contains("native") || element.getElementsByTag("span").text().contains("synchronized") || element.getElementsByTag("span").text().contains("abstract") || element.getElementsByTag("span").text().contains("threadsafe") || element.getElementsByTag("span").text().contains("transient")) { element.select("span.keyword").remove(); if (!element.text().contains("=") && !element.text().contains(".") && !element.text().contains("@")) { String[] s = element.text().split(" "); for (int i = 0; i < s.length; i++) { if (s[i].contains("(")) { aux = s[i].toCharArray(); for (int j = 0; j < aux.length; j++) { if (aux[j] == '(') { for (int k = j; k < aux.length; k++) { aux[k] = ' '; } break; } sbMetodo.append(aux[j]); } metodoTemp = sbMetodo.toString(); if (!metodoTemp.isEmpty()) { metodo = metodoTemp.replaceAll("\r", "").replaceAll("\t", "").replaceAll("\n", ""); sbMetodo.delete(0, aux.length); informacoes = new Informacoes(classe, metodo, Integer.parseInt(auxLinha)); inf.add(informacoes); } } } } } // --------------------------- Fim Verifica Mtodo ------------------------------------ } // } } /* for(int i=0; i<inf.size(); i++){ System.out.println("Classe:"+inf.get(i).getClasse()+" Metodo:"+inf.get(i).getMetodo()+" Linha: "+inf.get(i).getLinha()); } // /* for(Map.Entry<String,Informacoes> entry : inf.entrySet()) { String key = entry.getKey(); int value = entry.getValue().getLinha(); String metodov = entry.getValue().getMetodo(); String classev = entry.getValue().getClasse(); System.out.println(key + " => " + classev+ " => " +metodov+ " => " +value); }*/ }
From source file:org.csploit.android.core.UpdateService.java
/** * extract an archive into a directory// w w w . j av a2s . co m * * @throws IOException if some I/O error occurs * @throws java.util.concurrent.CancellationException if task is cancelled by user * @throws java.lang.InterruptedException when the the running thread get cancelled. */ private void extract() throws CancellationException, RuntimeException, IOException, InterruptedException, ChildManager.ChildNotStartedException { ArchiveInputStream is = null; ArchiveEntry entry; CountingInputStream counter; OutputStream outputStream = null; File f, inFile; File[] list; String name; String envPath; final StringBuffer sb = new StringBuffer(); int mode; int count; long total; boolean isTar, r, w, x, isElf, isScript; short percentage, old_percentage; Child which; DiffMatchPatch dmp; if (mCurrentTask.path == null || mCurrentTask.outputDir == null) return; mBuilder.setContentTitle(getString(R.string.extracting)).setContentText("").setContentInfo("") .setSmallIcon(android.R.drawable.ic_popup_sync).setProgress(100, 0, false); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); Logger.info(String.format("extracting '%s' to '%s'", mCurrentTask.path, mCurrentTask.outputDir)); envPath = null; which = null; try { if (mCurrentTask.fixShebang) { which = System.getTools().raw.async("which env", new Raw.RawReceiver() { @Override public void onNewLine(String line) { sb.delete(0, sb.length()); sb.append(line); } }); } inFile = new File(mCurrentTask.path); total = inFile.length(); counter = new CountingInputStream(new FileInputStream(inFile)); is = openArchiveStream(counter); isTar = mCurrentTask.archiver.equals(archiveAlgorithm.tar); old_percentage = -1; dmp = (mCurrentTask.patches != null && mCurrentTask.patches.size() > 0) ? new DiffMatchPatch() : null; f = new File(mCurrentTask.outputDir); if (f.exists() && f.isDirectory() && (list = f.listFiles()) != null && list.length > 2) wipe(); if (mCurrentTask.fixShebang) { if (execShell(which, "cancelled while retrieving env path") != 0) { throw new RuntimeException("cannot find 'env' executable"); } envPath = sb.toString(); } while (mRunning && (entry = is.getNextEntry()) != null) { name = entry.getName().replaceFirst("^\\./?", ""); if (mCurrentTask.skipRoot) { if (name.contains("/")) name = name.substring(name.indexOf('/') + 1); else if (entry.isDirectory()) continue; } f = new File(mCurrentTask.outputDir, name); isElf = isScript = false; if (entry.isDirectory()) { if (!f.exists()) { if (!f.mkdirs()) { throw new IOException( String.format("Couldn't create directory '%s'.", f.getAbsolutePath())); } } } else { byte[] buffer = null; byte[] writeMe = null; // patch the file if (dmp != null && mCurrentTask.patches.containsKey(name)) { buffer = new byte[(int) entry.getSize()]; IOUtils.readFully(is, buffer); writeMe = buffer = ((String) dmp.patch_apply(mCurrentTask.patches.get(name), new String(buffer))[0]).getBytes(); } outputStream = new FileOutputStream(f); // check il file is an ELF or a script if ((!isTar || mCurrentTask.fixShebang) && entry.getSize() > 4) { if (buffer == null) { writeMe = buffer = new byte[4]; IOUtils.readFully(is, buffer); if (buffer[0] == 0x7F && buffer[1] == 0x45 && buffer[2] == 0x4C && buffer[3] == 0x46) { isElf = true; } else if (buffer[0] == '#' && buffer[1] == '!') { isScript = true; ByteArrayOutputStream firstLine = new ByteArrayOutputStream(); int newline = -1; // assume that '\n' is more far then 4 chars. firstLine.write(buffer); buffer = new byte[1024]; count = 0; while (mRunning && (count = is.read(buffer)) >= 0 && (newline = Arrays.binarySearch(buffer, 0, count, (byte) 0x0A)) < 0) { firstLine.write(buffer, 0, count); } if (!mRunning) { throw new CancellationException("cancelled while searching for newline."); } else if (count < 0) { newline = count = 0; } else if (newline < 0) { newline = count; } firstLine.write(buffer, 0, newline); firstLine.close(); byte[] newFirstLine = new String(firstLine.toByteArray()) .replace("/usr/bin/env", envPath).getBytes(); writeMe = new byte[newFirstLine.length + (count - newline)]; java.lang.System.arraycopy(newFirstLine, 0, writeMe, 0, newFirstLine.length); java.lang.System.arraycopy(buffer, newline, writeMe, newFirstLine.length, count - newline); } } else { if (buffer[0] == 0x7F && buffer[1] == 0x45 && buffer[2] == 0x4C && buffer[3] == 0x46) { isElf = true; } else if (buffer[0] == '#' && buffer[1] == '!') { isScript = true; int newline = Arrays.binarySearch(buffer, (byte) 0x0A); if (newline < 0) newline = buffer.length; byte[] newFirstLine = new String(buffer, 0, newline) .replace("/usr/bin/env", envPath).getBytes(); writeMe = new byte[buffer.length + (newFirstLine.length - newline)]; java.lang.System.arraycopy(newFirstLine, 0, writeMe, 0, newFirstLine.length); java.lang.System.arraycopy(buffer, newline, writeMe, newFirstLine.length, newFirstLine.length - newline); } } } if (writeMe != null) { outputStream.write(writeMe); } IOUtils.copy(is, outputStream); outputStream.close(); outputStream = null; percentage = (short) (((double) counter.getBytesRead() / total) * 100); if (percentage != old_percentage) { mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%"); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); old_percentage = percentage; } } // Zip does not store file permissions. if (isTar) { mode = ((TarArchiveEntry) entry).getMode(); r = (mode & 0400) > 0; w = (mode & 0200) > 0; x = (mode & 0100) > 0; } else if (isElf || isScript) { r = w = x = true; } else { continue; } if (!f.setExecutable(x, true)) { Logger.warning(String.format("cannot set executable permission of '%s'", name)); } if (!f.setWritable(w, true)) { Logger.warning(String.format("cannot set writable permission of '%s'", name)); } if (!f.setReadable(r, true)) { Logger.warning(String.format("cannot set readable permission of '%s'", name)); } } if (!mRunning) throw new CancellationException("extraction cancelled."); Logger.info("extraction completed"); f = new File(mCurrentTask.outputDir, ".nomedia"); if (f.createNewFile()) Logger.info(".nomedia created"); mBuilder.setContentInfo("").setProgress(100, 100, true); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } finally { if (is != null) is.close(); if (outputStream != null) outputStream.close(); } }