List of usage examples for java.lang StringBuffer charAt
@Override public synchronized char charAt(int index)
From source file:architecture.common.util.TextUtils.java
/** * Returns a string that has whitespace removed from both ends of the * String, as well as duplicate whitespace removed from within the String. *//*from ww w .j a v a 2 s .c om*/ public final static String innerTrim(String s) { StringBuffer b = new StringBuffer(s); int index = 0; while ((b.length() != 0) && (b.charAt(0) == ' ')) { b.deleteCharAt(0); } while (index < b.length()) { if (Character.isWhitespace(b.charAt(index))) { if (((index + 1) < b.length()) && (Character.isWhitespace(b.charAt(index + 1)))) { b.deleteCharAt(index + 1); index--; // let's restart at this character! } } index++; } if (b.length() > 0) { int l = b.length() - 1; if (b.charAt(l) == ' ') { b.setLength(l); } } String result = b.toString(); return result; }
From source file:net.sf.jabref.groups.structure.KeywordGroup.java
/** * Removes matches of searchString in the entry's field. This is only * possible if the search expression is not a regExp. *//*from w w w. j av a2 s. c om*/ private void removeMatches(BibEntry entry) { if (!entry.hasField(searchField)) { return; // nothing to modify } String content = entry.getField(searchField); StringBuffer sbOrig = new StringBuffer(content); StringBuffer sbLower = new StringBuffer(content.toLowerCase()); StringBuffer haystack = caseSensitive ? sbOrig : sbLower; String needle = caseSensitive ? searchExpression : searchExpression.toLowerCase(); int i; int j; int k; final String separator = Globals.prefs.get(JabRefPreferences.GROUP_KEYWORD_SEPARATOR); while ((i = haystack.indexOf(needle)) >= 0) { sbOrig.replace(i, i + needle.length(), ""); sbLower.replace(i, i + needle.length(), ""); // reduce spaces at i to 1 j = i; k = i; while (((j - 1) >= 0) && (separator.indexOf(haystack.charAt(j - 1)) >= 0)) { --j; } while ((k < haystack.length()) && (separator.indexOf(haystack.charAt(k)) >= 0)) { ++k; } sbOrig.replace(j, k, (j >= 0) && (k < sbOrig.length()) ? separator : ""); sbLower.replace(j, k, (j >= 0) && (k < sbOrig.length()) ? separator : ""); } String result = sbOrig.toString().trim(); if (result.isEmpty()) { entry.clearField(searchField); } else { entry.setField(searchField, result); } }
From source file:org.lockss.extractor.GoslingHtmlLinkExtractor.java
/** * Perform tag-specfic link extraction.//from w w w.j a v a 2 s.com * Method overridden in many plugin-specific subclasses; change with care */ protected String extractLinkFromTag(StringBuffer link, ArchivalUnit au, LinkExtractor.Callback cb) throws IOException { //String returnStr = null; switch (link.charAt(0)) { case 'a': //<a href=http://www.yahoo.com> case 'A': //optimization, since we just have to check a single char if (Character.isWhitespace(link.charAt(1))) { return (getAttributeValue(HREF, link)); } if (beginsWithTag(link, APPLETTAG)) { return (getAttributeValue(CODE, link)); } if (beginsWithTag(link, AREATAG)) { return (getAttributeValue(HREF, link)); } break; case 'f': //<frame src=frame1.html> case 'F': if (beginsWithTag(link, FRAMETAG)) { return (getAttributeValue(SRC, link)); } break; case 'o': //<object codebase=blah.java> or <option value="blah.html"> case 'O': if (beginsWithTag(link, OBJECTTAG)) { return (getAttributeValue(CODEBASE, link)); } if (beginsWithTag(link, OPTIONTAG)) { String optionAttribute = getOptionAttribute(au); if (optionAttribute != null) { return (getAttributeValue(optionAttribute, link)); } } break; case 'i': //<img src=image.gif> case 'I': if (beginsWithTag(link, IMGTAG)) { return (getAttributeValue(SRC, link)); } if (beginsWithTag(link, IFRAMETAG)) { return (getAttributeValue(SRC, link)); } break; case 'e': //<embed src=image.gif> case 'E': if (beginsWithTag(link, EMBEDTAG)) { return (getAttributeValue(SRC, link)); } break; case 'l': //<link href=blah.css> case 'L': if (beginsWithTag(link, LINKTAG)) { return (getAttributeValue(HREF, link)); } break; case 'b': //<body background=background.gif> case 'B': //or <base href=http://www.example.com> if (beginsWithTag(link, BODYTAG)) { return (getAttributeValue(BACKGROUNDSRC, link)); } if (beginsWithTag(link, BASETAG)) { processBaseTag(link); } break; case 's': //<script src=blah.js> or <style type="text/css">...CSS...</style> case 'S': if (beginsWithTag(link, SCRIPTTAG)) { lastTagWasScript = true; return (getAttributeValue(SRC, link)); } if (beginsWithTag(link, STYLETAG) && CurrentConfig.getBooleanParam(PARAM_PARSE_CSS, DEFAULT_PARSE_CSS)) { parseStyleContentsFromRing(au, cb); } break; case 'm': //<meta http-equiv="refresh" case 'M': //"content="0; url=http://example.com/blah.html"> if (beginsWithTag(link, METATAG)) { String httpEquiv = getAttributeValue(HTTP_EQUIV, link); if (REFRESH.equalsIgnoreCase(httpEquiv)) { String content = getAttributeValue(HTTP_EQUIV_CONTENT, link); return HtmlUtil.extractMetaRefreshUrl(content); } } break; case 't': // <table background=back.gif> or <td background=back.gif> or <th background=back.gif> case 'T': // See http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/background_2.asp if (beginsWithTag(link, TABLETAG) || beginsWithTag(link, TDTAG) || beginsWithTag(link, THTAG)) { return (getAttributeValue(BACKGROUNDSRC, link)); } break; } return null; }
From source file:com.netspective.commons.text.TextUtils.java
public String fixupTableNameCase(String tableNameOrig) { if (null == tableNameOrig) return null; StringBuffer tableNameBuf = new StringBuffer(tableNameOrig.toLowerCase()); boolean capNext = false; for (int i = 0; i < tableNameBuf.length(); i++) { if (tableNameBuf.charAt(i) == '_') capNext = true;//from w w w . j a v a 2 s .c o m else { if (i == 0 || capNext) { tableNameBuf.setCharAt(i, Character.toUpperCase(tableNameBuf.charAt(i))); capNext = false; } } } return tableNameBuf.toString(); }
From source file:org.wso2.carbon.dashboard.portal.core.datasource.DataBaseInitializer.java
/** * Checks that a string buffer ends up with a given string. It may sound * trivial with the existing/*from w w w.ja v a 2 s .co m*/ * JDK API but the various implementation among JDKs can make those * methods extremely resource intensive * and perform poorly due to massive memory allocation and copying. See * * @param buffer the buffer to perform the check on * @param suffix the suffix * @return <code>true</code> if the character sequence represented by the * argument is a suffix of the character sequence represented by * the StringBuffer object; <code>false</code> otherwise. Note that the * result will be <code>true</code> if the argument is the * empty string. */ private boolean checkStringBufferEndsWith(StringBuffer buffer, String suffix) { if (suffix.length() > buffer.length()) { return false; } // this loop is done on purpose to avoid memory allocation performance // problems on various JDKs // StringBuffer.lastIndexOf() was introduced in jdk 1.4 and // implementation is ok though does allocation/copying // StringBuffer.toString().endsWith() does massive memory // allocation/copying on JDK 1.5 // See http://issues.apache.org/bugzilla/show_bug.cgi?id=37169 int endIndex = suffix.length() - 1; int bufferIndex = buffer.length() - 1; while (endIndex >= 0) { if (buffer.charAt(bufferIndex) != suffix.charAt(endIndex)) { return false; } bufferIndex--; endIndex--; } return true; }
From source file:org.pentaho.platform.plugin.action.jasperreports.JasperReportsComponent.java
/** * Creates and initializes the appropriate exporter for producing output. * All channel specific export options will be set for the exporter. * //from w w w. ja va2 s . c o m * @param outputType * the channel (pdf or html) to use when exporting * @param reportName * used to create a unique name for the directory to store images * in. Should be something unique to the invocation, such as the * session id, but I don't know how to get that from the Pentaho * API yet. * * @return the exporter to use, or <code>null</code> if the output type is * not valid. * * TODO: replace reportName with something unique, like session id. */ private JRExporter getExporter(String outputType, String reportName) { JRExporter exporter = null; IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext(); if (HTML.equals(outputType)) { String removeEmptyRows = getStringSetting("removeEmptyRows"); //$NON-NLS-1$ exporter = new JRHtmlExporter(); exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE); if (removeEmptyRows != null && "true".equalsIgnoreCase(removeEmptyRows)) { //$NON-NLS-1$ exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); } String imageUrl = requestContext.getContextPath() + getStringSetting(IMAGE_URL); //$NON-NLS-1$ //$NON-NLS-2$ StringBuffer tempImgPath = new StringBuffer() .append(PentahoSystem.getApplicationContext().getSolutionPath(getStringSetting(IMAGE_DIR))); if (!(tempImgPath.charAt(tempImgPath.length() - 1) == File.separatorChar)) { tempImgPath.append(File.separator); } tempImgPath.append(reportName).append(File.separator); String imagePath = tempImgPath.toString(); File imageDir = new File(imagePath); imageDir.mkdirs(); exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR, imageDir); // exporter.setParameter(JRHtmlExporter.IMAGES_URI, imageUrl + // reportName ); //$NON-NLS-1$ exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageUrl + reportName + "/"); //$NON-NLS-1$ exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE); if (debug) { debug(Messages.getString("JasperReport.DEBUG_IMAGE_DIRECTORY", imagePath)); //$NON-NLS-1$ } } else if (PDF.equals(outputType)) { exporter = new JRPdfExporter(); } else if (XLS.equals(outputType)) { exporter = new JRXlsExporter(); // Some cleaning in order to make excel reports look better exporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE); exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.TRUE); exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE); } else if (CSV.equals(outputType)) { exporter = new JRCsvExporter(); } else if (XML.equals(outputType)) { exporter = new JRXmlExporter(); } else if (TXT.equals(outputType)) { exporter = new JRTextExporter(); // Add required parameters exporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, new Integer("120")); //$NON-NLS-1$ exporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, new Integer("120")); //$NON-NLS-1$ } else if (RTF.equals(outputType)) { exporter = new JRRtfExporter(); } return exporter; }
From source file:com.arduino2fa.xbee.ReceivePacket.java
private ReceivePacket() throws Exception { XBee xbee = new XBee(); int count = 0; int errors = 0; // Transmit stuff final int timeout = 5000; int ackErrors = 0; int ccaErrors = 0; int purgeErrors = 0; long now;//from w ww.j a v a2s . c om // HTTP stuff CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpHost httpHost = new HttpHost("ec2-54-186-213-97.us-west-2.compute.amazonaws.com", 3000, "http"); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()), new UsernamePasswordCredentials("admin", "admin") // TODO get from command line ); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); BasicScheme basicScheme = new BasicScheme(); authCache.put(httpHost, basicScheme); // Add AuthCache to the execution context HttpClientContext httpClientContext = HttpClientContext.create(); httpClientContext.setCredentialsProvider(credentialsProvider); httpClientContext.setAuthCache(authCache); HttpGet httpGet = new HttpGet("/token-requests/1"); CloseableHttpResponse httpResponse; BufferedReader br; StringBuffer result; String line; try { // Connect to the XBee xbee.open(XbeeConfig.PORT, XbeeConfig.BAUD_RATE); now = System.currentTimeMillis(); // Loop indefinitely; sleeps for a few seconds at the end of every iteration while (true) { // Check if there are queued tx requests on the server httpResponse = httpClient.execute(httpHost, httpGet, httpClientContext); br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); result = new StringBuffer(); while ((line = br.readLine()) != null) { result.append(line); } // Check if the result is a JSON object if (result.charAt(0) != '{') { log.error("Result " + result.toString() + " is not a JSON object"); continue; } JSONObject object = (JSONObject) JSONValue.parse(result.toString()); if (object != null) { Long time = (Long) object.get("time"); // Check if the request is a new one (created after last check) if (time > last) { String token = (String) object.get("token"); byte[] tokenHex = SimpleCrypto.toByte(token); int[] payload = new int[] { tokenHex[0], tokenHex[1], tokenHex[2] }; XBeeAddress16 destination = new XBeeAddress16(0xFF, 0xFF); TxRequest16 tx = new TxRequest16(destination, payload); try { log.info("sending tx request with payload: " + token); XBeeResponse response = xbee.sendSynchronous(tx, timeout); if (response.getApiId() != ApiId.TX_STATUS_RESPONSE) { log.debug("expected tx status but received " + response); } else { log.debug("got tx status"); if (((TxStatusResponse) response).getFrameId() != tx.getFrameId()) { throw new RuntimeException("frame id does not match"); } if (((TxStatusResponse) response).getStatus() != TxStatusResponse.Status.SUCCESS) { errors++; if (((TxStatusResponse) response).isAckError()) { ackErrors++; } else if (((TxStatusResponse) response).isCcaError()) { ccaErrors++; } else if (((TxStatusResponse) response).isPurged()) { purgeErrors++; } log.debug("Tx status failure with status: " + ((TxStatusResponse) response).getStatus()); } else { // success log.debug("Success. count is " + count + ", errors is " + errors + ", in " + (System.currentTimeMillis() - now) + ", ack errors " + ackErrors + ", ccaErrors " + ccaErrors + ", purge errors " + purgeErrors); } count++; } } catch (XBeeTimeoutException e) { e.printStackTrace(); } } } last = System.currentTimeMillis(); httpGet.releaseConnection(); // Delay Thread.sleep(2000); } } finally { xbee.close(); } }
From source file:org.apache.lucene.analysis.de.GermanStemmer.java
/** * suffix stripping (stemming) on the current term. The stripping is reduced * to the seven "base" suffixes "e", "s", "n", "t", "em", "er" and * "nd", * from which all regular suffixes are build of. The simplification causes * some overstemming, and way more irregular stems, but still provides * unique. discriminators in the most of those cases. The algorithm is * context free, except of the length restrictions. *//*from w w w .j a va2 s . co m*/ private void strip(StringBuffer buffer) { boolean doMore = true; while (doMore && buffer.length() > 3) { if ((buffer.length() + substCount > 5) && buffer.substring(buffer.length() - 2, buffer.length()).equals("nd")) { buffer.delete(buffer.length() - 2, buffer.length()); } else if ((buffer.length() + substCount > 4) && buffer.substring(buffer.length() - 2, buffer.length()).equals("em")) { buffer.delete(buffer.length() - 2, buffer.length()); } else if ((buffer.length() + substCount > 4) && buffer.substring(buffer.length() - 2, buffer.length()).equals("er")) { buffer.delete(buffer.length() - 2, buffer.length()); } else if (buffer.charAt(buffer.length() - 1) == 'e') { buffer.deleteCharAt(buffer.length() - 1); } else if (buffer.charAt(buffer.length() - 1) == 's') { buffer.deleteCharAt(buffer.length() - 1); } else if (buffer.charAt(buffer.length() - 1) == 'n') { buffer.deleteCharAt(buffer.length() - 1); } // "t" occurs only as suffix of verbs. else if (buffer.charAt(buffer.length() - 1) == 't') { buffer.deleteCharAt(buffer.length() - 1); } else { doMore = false; } } }
From source file:com.fiorano.openesb.application.application.Route.java
/** * Converts to new DMI//from w w w .j a v a 2s . com * @param that old Route DMI */ public void convert(com.fiorano.openesb.application.aps.Route that) { name = that.getRouteGUID(); if (!Pattern.matches("([a-zA-Z0-9_]+)", name)) { StringBuffer nameBuff = new StringBuffer(name); for (int i = 0; i < nameBuff.length(); i++) { if (!Pattern.matches("([a-zA-Z0-9_]+)", String.valueOf(nameBuff.charAt(i)))) { nameBuff.setCharAt(i, '_'); } } name = nameBuff.toString(); } sourceServiceInstance = that.getSrcServInst(); sourcePortInstance = that.getSrcPortName(); targetServiceInstance = that.getTrgtServInst(); targetPortInstance = that.getTrgtPortName(); shortDescription = that.getShortDescription(); longDescription = that.getLongDescription(); durable = that.isDurable(); if (!StringUtils.isEmpty(that.getTransformationXSL()) || !StringUtils.isEmpty(that.getMessageTransformationXSL())) { messageTransformation = new MessageTransformation(); messageTransformation.convert(that); } Iterator iter = that.getSelectors().entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String type = (String) entry.getKey(); if (com.fiorano.openesb.application.aps.Route.JMS_SELECTOR.equalsIgnoreCase(type)) selectors.put(SELECTOR_JMS, entry.getValue()); else if (com.fiorano.openesb.application.aps.Route.SENDER_SELECTOR.equalsIgnoreCase(type)) selectors.put(SELECTOR_SENDER, entry.getValue()); else { XPathSelector selector = new XPathSelector(); if (entry.getValue() instanceof XPathDmi) selector.convert((XPathDmi) entry.getValue()); else selector.setXPath((String) entry.getValue()); selectors.put(com.fiorano.openesb.application.aps.Route.APP_CONTEXT_XPATH.equalsIgnoreCase(type) ? SELECTOR_APPLICATION_CONTEXT : SELECTOR_BODY, selector); } } }
From source file:com.wabacus.system.component.application.report.configbean.crosslist.AbsCrossListReportColAndGroupBean.java
protected void afterGetRuntimeColGroups(CrossListReportType crossListReportType, Map<String, Boolean> mDynamicColGroupDisplayType, StringBuffer allDynColConditonsBuf, StringBuffer dynSelectedColsBuf, List lstAllRuntimeChildren, List<ColBean> lstAllRuntimeColBeans, List lstDynChildren, AbsReportDataPojo headDataObj) { if (headDataObj != null) { headDataObj.format();//from w ww. java 2 s . c om getRealDisplayLabel(crossListReportType.getReportRequest(), headDataObj, lstDynChildren); } if (dynSelectedColsBuf.length() > 0 && dynSelectedColsBuf.charAt(dynSelectedColsBuf.length() - 1) == ',') { dynSelectedColsBuf.deleteCharAt(dynSelectedColsBuf.length() - 1); } String selectedCols = dynSelectedColsBuf.toString(); if (this.hasDisplayStatisBeansOfReport(mDynamicColGroupDisplayType)) { StringBuffer tmpBuf = new StringBuffer(); String allColConditions = allDynColConditonsBuf.toString().trim(); if (allColConditions.endsWith("or")) allColConditions = allColConditions.substring(0, allColConditions.length() - 2); createStatisForWholeRow(crossListReportType, tmpBuf, lstDynChildren, allColConditions, mDynamicColGroupDisplayType); if (!tmpBuf.toString().trim().equals("")) { if (selectedCols.trim().equals("")) { selectedCols = tmpBuf.toString(); } else { selectedCols = selectedCols + "," + tmpBuf.toString(); } } } if (!selectedCols.trim().equals("")) { createAllDisplayChildren(lstAllRuntimeColBeans, lstAllRuntimeChildren, lstDynChildren); } crossListReportType.addDynamicSelectCols(this, selectedCols); }