List of usage examples for java.lang StringBuffer replace
@Override public synchronized StringBuffer replace(int start, int end, String str)
From source file:fedora.server.access.dissemination.DisseminationService.java
/** * <p>/*from ww w . j av a2 s . c o m*/ * Removes any optional userInputParms which remain in the dissemination * URL. This occurs when a method has optional parameters and the user does * not supply a value for one or more of the optional parameters. The result * is a syntax similar to "parm=(PARM_BIND_KEY)". This method removes these * non-supplied optional parameters from the string. * </p> * * @param dissURL * String to be processed. * @return An edited string with parameters removed where no value was * specified for any optional parameters. */ private String stripParms(String dissURL) { // if no parameters, simply return passed in string. if (dissURL.indexOf("?") == -1) { return dissURL; } String requestURI = dissURL.substring(0, dissURL.indexOf("?") + 1); String parmString = dissURL.substring(dissURL.indexOf("?") + 1, dissURL.length()); String[] parms = parmString.split("&"); StringBuffer sb = new StringBuffer(); for (String element : parms) { int len = element.length() - 1; if (element.lastIndexOf(")") != len) { sb.append(element + "&"); } } int index = sb.lastIndexOf("&"); if (index != -1 && index + 1 == sb.length()) { sb.replace(index, sb.length(), ""); } return requestURI + sb.toString(); }
From source file:org.ralasafe.db.sql.Query.java
/** * Add line breaker at propriety positions, to format for web view * @param script/*from w w w. j a va2 s . co m*/ * @return */ private String format(String script) { int maxInLine = 80; int lengthOfLine = 0; int indexOfTheLatestSpaceOrComma = 0; char[] dst = new char[script.length()]; script.getChars(0, script.length(), dst, 0); StringBuffer buf = new StringBuffer(); char replacedChar = ' '; for (int i = 0; i < dst.length; i++, lengthOfLine++) { char curChar = dst[i]; buf.append(curChar); if (curChar == '\n') { // reset counter lengthOfLine = 0; continue; } if (curChar == ' ' || curChar == '\t' || curChar == ',') { replacedChar = curChar; indexOfTheLatestSpaceOrComma = buf.length() - 1; } if (lengthOfLine == maxInLine) { // break line if (replacedChar == ',') { buf.replace(indexOfTheLatestSpaceOrComma, indexOfTheLatestSpaceOrComma + 1, ",\n "); } else { buf.replace(indexOfTheLatestSpaceOrComma, indexOfTheLatestSpaceOrComma + 1, "\n "); } lengthOfLine = (buf.length() - indexOfTheLatestSpaceOrComma + 1); } } return buf.toString(); }
From source file:net.mlw.vlh.adapter.jdbc.util.ConfigurableStatementBuilder.java
/** * @see net.mlw.vlh.adapter.jdbc.util.StatementBuilder#generate(java.sql.Connection, java.lang.StringBuffer, java.util.Map, boolean) *//* ww w .j a v a 2s . c o m*/ public PreparedStatement generate(Connection conn, StringBuffer query, Map whereClause, boolean scrollable) throws SQLException, ParseException { if (!init) { init(); } if (whereClause == null) { whereClause = Collections.EMPTY_MAP; } for (Iterator iter = textManipulators.iterator(); iter.hasNext();) { TextManipulator manipulator = (TextManipulator) iter.next(); manipulator.manipulate(query, whereClause); } LinkedList arguments = new LinkedList(); // Replace any "{key}" with the value in the whereClause Map, // then placing the value in the partameters list. for (int i = 0, end = 0, start; ((start = query.toString().indexOf('{', end)) >= 0); i++) { end = query.toString().indexOf('}', start); String key = query.substring(start + 1, end); Object value = whereClause.get(key); if (value == null) { throw new NullPointerException("Property '" + key + "' was not provided."); } arguments.add(new NamedPair(key, value)); Setter setter = getSetter(key); query.replace(start, end + 1, setter.getReplacementString(value)); end -= (key.length() + 2); } PreparedStatement statement = null; if (scrollable) { statement = conn.prepareStatement(query.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); } else { statement = conn.prepareStatement(query.toString()); } int index = 1; // Now set all the patameters on the statement. for (Iterator iter = arguments.iterator(); iter.hasNext();) { NamedPair namedPair = (NamedPair) iter.next(); Setter setter = getSetter(namedPair.getName()); try { index = setter.set(statement, index, namedPair.getValue()); } catch (RuntimeException e) { String message = "Cannot set value of " + namedPair.getName() + " (setter = " + setter + ")"; LOGGER.error(message, e); throw new RuntimeException(message, e); } } return statement; }
From source file:com.photon.phresco.impl.DrupalApplicationProcessor.java
public void replaceSqlBlock(File versionFile, String fileName, String moduleName, String queryString) throws PhrescoException, IOException { BufferedReader buff = null;/*from w w w . j a va 2 s . c o m*/ try { File scriptFile = new File(versionFile + File.separator + fileName); StringBuffer sb = new StringBuffer(); if (scriptFile.isFile()) { // if script file is available need to replace the content buff = new BufferedReader(new FileReader(scriptFile)); String readBuff = buff.readLine(); String sectionStarts = MODULE_START_TAG + moduleName + START_MODULE_END_TAG; String sectionEnds = MODULE_START_TAG + moduleName + END_MODULE_END_TAG; while (readBuff != null) { sb.append(readBuff); sb.append(LINE_BREAK); readBuff = buff.readLine(); } int cnt1 = sb.indexOf(sectionStarts); int cnt2 = sb.indexOf(sectionEnds); if (cnt1 != -1 || cnt2 != -1) { sb.replace(cnt1 + sectionStarts.length(), cnt2, LINE_BREAK + queryString + LINE_BREAK); } else { // if this module is not added already in the file and need to add this config alone sb.append(LINE_BREAK + DOUBLE_HYPHEN + LINE_BREAK); sb.append(MODULE_START_TAG + moduleName + START_MODULE_END_TAG + LINE_BREAK); sb.append(queryString); sb.append(LINE_BREAK); sb.append(MODULE_START_TAG + moduleName + END_MODULE_END_TAG + LINE_BREAK); sb.append(DOUBLE_HYPHEN + LINE_BREAK); } } else { // else construct the format and write // query string buffer sb.append( "CREATE TABLE IF NOT EXISTS `variable` (`name` varchar(128) NOT NULL DEFAULT '' COMMENT 'The name of the variable.', `value` longblob NOT NULL COMMENT 'The value of the variable.', PRIMARY KEY (`name`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Named variable/value pairs created by Drupal core or any...';" + LINE_BREAK); sb.append(DOUBLE_HYPHEN + LINE_BREAK); sb.append(MODULE_START_TAG + moduleName + START_MODULE_END_TAG + LINE_BREAK); sb.append(queryString); sb.append(LINE_BREAK); sb.append(MODULE_START_TAG + moduleName + END_MODULE_END_TAG + LINE_BREAK); sb.append(DOUBLE_HYPHEN + LINE_BREAK); } FileUtils.writeStringToFile(scriptFile, sb.toString()); } catch (Exception e) { throw new PhrescoException(e); } finally { if (buff != null) { buff.close(); } } }
From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java
private String cleanCommandLineArgs(String vmName) { vmName = vmName.replaceAll("\"", ""); // Strip any quotes from the name (needed for running on Jenkins server) StringBuffer buff = new StringBuffer(vmName); int argIndex = -1; while ((argIndex = buff.indexOf("-D")) != -1) { // While there's a command line argument in the string int argEnd = -1; if ((argEnd = buff.indexOf(" ", argIndex)) == -1) { // If this argument is at the end of the display name then clean to the end rather than to next white space argEnd = buff.length();//from w w w . j a v a 2 s. com } buff.replace(argIndex - 1, argEnd, ""); // remove contents of buffer between space before arg starts and the next white space/end of buffer } return buff.toString(); }
From source file:org.kuali.ole.sys.document.workflow.OLESearchableAttribute.java
@Override public List<DocumentAttribute> extractDocumentAttributes(ExtensionDefinition extensionDefinition, DocumentWithContent documentWithContent) { if (LOG.isDebugEnabled()) { LOG.debug("extractDocumentAttributes( " + extensionDefinition + ", " + documentWithContent + " )"); }/*from w w w.ja v a 2 s . c o m*/ List<DocumentAttribute> searchAttrValues = super.extractDocumentAttributes(extensionDefinition, documentWithContent); String docId = documentWithContent.getDocument().getDocumentId(); DocumentService docService = SpringContext.getBean(DocumentService.class); Document doc = null; try { doc = docService.getByDocumentHeaderIdSessionless(docId); } catch (WorkflowException we) { } if (doc != null) { if (doc instanceof AmountTotaling) { DocumentAttributeDecimal.Builder searchableAttributeValue = DocumentAttributeDecimal.Builder .create(OLEPropertyConstants.FINANCIAL_DOCUMENT_TOTAL_AMOUNT); searchableAttributeValue.setValue(((AmountTotaling) doc).getTotalDollarAmount().bigDecimalValue()); searchAttrValues.add(searchableAttributeValue.build()); } if (doc instanceof AccountingDocument) { AccountingDocument accountingDoc = (AccountingDocument) doc; searchAttrValues.addAll(harvestAccountingDocumentSearchableAttributes(accountingDoc)); } boolean indexedLedgerDoc = false; if (doc instanceof GeneralLedgerPostingDocument && !indexedLedgerDoc) { GeneralLedgerPostingDocument GLPostingDoc = (GeneralLedgerPostingDocument) doc; searchAttrValues.addAll(harvestGLPDocumentSearchableAttributes(GLPostingDoc)); } if (doc instanceof PurchasingAccountsPayableDocument) { PurchasingAccountsPayableDocument purchasingAccountsPayableDocument = (PurchasingAccountsPayableDocument) doc; searchAttrValues .addAll(harvestPurchasingAccountsPayableDocument(purchasingAccountsPayableDocument)); } if (doc instanceof OleLineItemReceivingDocument | doc instanceof OleCorrectionReceivingDocument) { ReceivingDocument receivingDocument = (ReceivingDocument) doc; searchAttrValues.addAll(harvestReceivingDocument(receivingDocument)); } if (doc instanceof OleInvoiceDocument) { StringBuffer purchaseOrderDocumentNums = new StringBuffer(); OleInvoiceDocument invoiceDocument = (OleInvoiceDocument) doc; for (Object purApItem : invoiceDocument.getItems()) { OleInvoiceItem invoiceItem = (OleInvoiceItem) purApItem; if (invoiceItem.getPurchaseOrderIdentifier() != null) { purchaseOrderDocumentNums.append(invoiceItem.getPurchaseOrderIdentifier().toString() + ","); } } int len = purchaseOrderDocumentNums.lastIndexOf(","); if (len > 0) { purchaseOrderDocumentNums.replace(len, len + 1, " "); } DocumentAttributeString.Builder poDocNumSearchableAttributeValue = DocumentAttributeString.Builder .create(OleSelectConstant.InvoiceSearch.PO_DOC_NUMS); poDocNumSearchableAttributeValue.setValue(purchaseOrderDocumentNums.toString()); searchAttrValues.add(poDocNumSearchableAttributeValue.build()); DateFormat sourceFormat = new SimpleDateFormat("dd-MM-yyyy"); String invoiceDate = sourceFormat.format(invoiceDocument.getInvoiceDate()); String invoicePayDate = sourceFormat.format(invoiceDocument.getInvoicePayDate()); DocumentAttributeString.Builder invDateSearchableAttributeValue = DocumentAttributeString.Builder .create(OleSelectConstant.InvoiceSearch.PO_DIS_INV_DT); invDateSearchableAttributeValue.setValue(invoiceDate); searchAttrValues.add(invDateSearchableAttributeValue.build()); DocumentAttributeString.Builder invPayDateSearchableAttributeValue = DocumentAttributeString.Builder .create(OleSelectConstant.InvoiceSearch.PO_DIS_INV_PAY_DT); invPayDateSearchableAttributeValue.setValue(invoicePayDate); searchAttrValues.add(invPayDateSearchableAttributeValue.build()); } } return searchAttrValues; }
From source file:com.ewcms.plugin.report.generate.factory.ChartFactory.java
/** * ??/* ww w. j a v a 2s . co m*/ * * @param chartParam * @param sql * @return * @throws ConvertException * @throws ClassNotFoundException * @throws TypeHandlerException */ @SuppressWarnings("unchecked") private String replaceParam(Map<String, String> pageParams, Set<Parameter> paramSets, String expression, Boolean isSql) throws ConvertException, ClassNotFoundException { if (paramSets == null || paramSets.size() == 0) { return expression; } Map<String, Object> chartParam = new HashMap<String, Object>(); if (pageParams == null || pageParams.size() == 0) { for (Parameter param : paramSets) { String value = param.getDefaultValue(); if (value == null) { continue; } String className = param.getClassName(); Class<Object> forName = (Class<Object>) Class.forName(className); Object paramValue = ConvertFactory.instance.convertHandler(forName).parse(value); chartParam.put(param.getEnName(), paramValue); } } else { for (Parameter param : paramSets) { String value = pageParams.get(param.getEnName()); if (value == null) { continue; } String className = param.getClassName(); Class<Object> forName = (Class<Object>) Class.forName(className); Object paramValue = ConvertFactory.instance.convertHandler(forName).parse(value); chartParam.put(param.getEnName(), paramValue); } } int beginIndex = 0; int endIndex = 0; StringBuffer sb = new StringBuffer(expression); for (int i = 0; i < sb.length(); i++) { String p = sb.substring(i, i + 1); if (p.equals("$")) { beginIndex = i; continue; } if (p.equals("}")) { endIndex = i; } if (endIndex > beginIndex) { String temp = sb.substring(beginIndex, endIndex + 1); Iterator<Entry<String, Object>> iterator = chartParam.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Object> e = (Map.Entry<String, Object>) iterator.next(); if (temp.indexOf(e.getKey(), 0) != -1) { Object value = e.getValue(); if (isSql) { if (value instanceof String) { sb = sb.replace(beginIndex, endIndex + 1, "'" + value + "'"); } else if (value instanceof Date) { sb = sb.replace(beginIndex, endIndex + 1, "'" + value + "'"); } else { sb = sb.replace(beginIndex, endIndex + 1, "" + value + ""); } } else { sb = sb.replace(beginIndex, endIndex + 1, "" + value + ""); } } } beginIndex = endIndex; } } return sb.toString(); }
From source file:fitnesserefactor.FitnesseRefactor.java
public void DeleteColumn(File file, int ColumnNum) throws IOException { String DeletedSubString;// ww w.j av a 2 s . c om DeletedSubLines = new ArrayList(); ArrayList noOfPipes = new ArrayList(); int k = 1; int t = 0; do { DeletedSubString = (String) FileUtils.readLines(file).get(p + k); if (DeletedSubString.isEmpty()) { break; } StringBuffer buff = new StringBuffer(DeletedSubString); for (int pipes = 0; pipes < DeletedSubString.length(); pipes++) { char ch = DeletedSubString.charAt(pipes); if (ch == '|') { noOfPipes.add(pipes); } } int TotalPipes = noOfPipes.size(); buff.replace((int) noOfPipes.get(ColumnNum - 1), (int) noOfPipes.get(ColumnNum), ""); DeletedSubLines.add(buff.toString()); k++; t++; } while (!DeletedSubLines.isEmpty()); }
From source file:fitnesserefactor.FitnesseRefactor.java
public void ReplaceValue(File file, String RowString) throws IOException { if (StartIndexTxt.getText() != null && EndIndexTxt.getText() != null) { String s = RowString;//from w w w . j a v a 2s . c o m StringBuffer buff = new StringBuffer(s); String RowSubString = s.substring(Integer.parseInt(StartIndexTxt.getText()), Integer.parseInt(EndIndexTxt.getText())); String RowSubString1 = RowSubString.replace(FindWhatTxt.getText().toString(), ReplaceWithTxt.getText().toString()); String NewRowString = buff.replace(Integer.parseInt(StartIndexTxt.getText()), Integer.parseInt(EndIndexTxt.getText()), RowSubString1).toString(); ReplacedLines.add(NewRowString); } else { String s = RowString; String RowSubString = s.replaceAll(FindWhatTxt.getText(), ReplaceWithTxt.getText()); ReplacedLines.add(RowSubString); } }
From source file:org.wso2.carbon.es.migration.MigrationDatabaseCreator.java
/** * executes content in SQL script/*from ww w . j a v a 2 s . 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()); } } }