List of usage examples for java.lang StringBuffer charAt
@Override public synchronized char charAt(int index)
From source file:org.mitre.honeyclient.WorkerThread.java
@Override public void run() { Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST, getName() + " accepted a new connection"); byte[] buf = new byte[1024]; StringBuffer buffer = new StringBuffer(); InputStream in = null;/*from ww w .j a v a 2 s .c o m*/ OutputStream out = null; try { in = socket.getInputStream(); out = socket.getOutputStream(); int len; boolean cont = true; while (cont) { len = in.read(buf); buffer.append(new String(buf, 0, len)); if (buffer.charAt(buffer.length() - 1) == '}') { cont = false; } Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST, getName() + " read: '" + new String(buf, 0, len) + "'"); Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST, getName() + " last charcted read: '" + Character.toString(buffer.charAt(buffer.length() - 1)) + "'"); Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST, getName() + " continue reading on port: " + Boolean.toString(cont)); } String text = buffer.toString(); File inputFile = null, outputFile = null; Response response = null; Request request = null; byte[] file_bytes; try { Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST, getName() + " request text : " + text); request = server.getMapper().readValue(text, Request.class); if ((FilenameUtils.getPath(request.getInputFilename()) != null) && (FilenameUtils.getPath(request.getOutputFilename()) != null) && (new File(request.getInputFilename()).exists())) { inputFile = new File(request.getInputFilename()); outputFile = new File(request.getOutputFilename()); } else if (request.getInputBase64FileContents() != null) { file_bytes = Base64.decodeBase64(request.getInputBase64FileContents().getBytes()); if (file_bytes.length > server.getFileSizeMax()) { throw new RuntimeException("Fail; File too big to process."); } FileUtils.writeByteArrayToFile( inputFile = File.createTempFile(FilenameUtils.getBaseName(request.getInputFilename()), "." + FilenameUtils.getExtension(request.getInputFilename())), file_bytes); outputFile = File.createTempFile(FilenameUtils.getBaseName(request.getOutputFilename()), "." + FilenameUtils.getExtension(request.getOutputFilename())); } else { throw new RuntimeException( "No Base64 encoded input file content, nor path provided with input filename."); } Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST, "calling convert of " + inputFile.getPath() + " to " + outputFile.getPath()); // TODO: convert using convert(File inputFile, File outputFile, DocumentFormat outputFormat), modify Request to handle server.getDocumentConverter().convert(inputFile, outputFile); if (!outputFile.exists()) throw new RuntimeException("The file could not be converted."); if (request.inputBase64FileContents != null) { byte[] outputFileBytes = new byte[(int) outputFile.length()]; FileInputStream f = new FileInputStream(outputFile.getPath()); f.read(outputFileBytes, 0, outputFileBytes.length); f.close(); String outputBase64encoded = new String(Base64.encodeBase64(outputFileBytes)); response = new Response("Success; output returned in Base64 format", request.getOutputFilename(), outputBase64encoded); } else { response = new Response("Success; output can found in the output file", request.getOutputFilename(), null); } } catch (RuntimeException e) { Logger.getLogger(WorkerThread.class.getName()).log(Level.SEVERE, e.toString()); response = new Response(e.getMessage(), null, null); //} catch (java.io.EOFException e) { //swallow } finally { if ((request != null) && (request.getInputBase64FileContents() != null)) { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } server.getMapper().writeValue(out, response); } } catch (Exception e) { // catch everything else Logger.getLogger(WorkerThread.class.getName()).log(Level.SEVERE, e.getMessage()); } finally { try { in.close(); out.close(); socket.close(); } catch (IOException e) { Logger.getLogger(WorkerThread.class.getName()).log(Level.SEVERE, null, e); } } Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST, getName() + " done"); }
From source file:org.apache.lucene.analysis.de.GermanStemmer.java
/** * Does some optimizations on the term. This optimisations are contextual. *///from ww w. ja v a 2 s.c o m private void optimize(StringBuffer buffer) { // Additional step for female plurals of professions and inhabitants. if (buffer.length() > 5 && buffer.substring(buffer.length() - 5, buffer.length()).equals("erin*")) { buffer.deleteCharAt(buffer.length() - 1); strip(buffer); } // Additional step for irregular plural nouns like "Matrizen -> Matrix". if (buffer.charAt(buffer.length() - 1) == ('z')) { buffer.setCharAt(buffer.length() - 1, 'x'); } }
From source file:com.enonic.vertical.engine.PresentationEngine.java
public Document getFusionBotQuery(String fusionBotUrl, String query, int siteNum, int page) { final String MESSAGE_00 = "Failed to query FusionBot search engine"; Document doc;//from w w w . j a va 2s. c o m try { StringBuffer urlStr = new StringBuffer(fusionBotUrl); urlStr.append("?keys="); StringBuffer sb = new StringBuffer(query.replace(' ', '+')); for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); if (c == '<') { sb.replace(i, i + 1, "<"); i += 5; } } urlStr.append(sb.toString()); urlStr.append("&sitenbr="); urlStr.append(siteNum); urlStr.append("&ct=0&xml=1&pos="); urlStr.append(page); URL url = new URL(urlStr.toString()); URLConnection urlConn = url.openConnection(); InputStream in = urlConn.getInputStream(); doc = XMLTool.domparse(in); } catch (Exception e) { VerticalEngineLogger.error(getClass(), 0, MESSAGE_00, e); doc = null; } if (doc == null) { doc = XMLTool.createDocument("noresult"); } return doc; }
From source file:com.ms.commons.log.MsSyslogAppender.java
/** * Gets HEADER portion of packet.// www. ja v a 2 s . c o m * * @param timeStamp number of milliseconds after the standard base time. * @return HEADER portion of packet, will be zero-length string if header is false. * @since 1.2.15 */ private String getPacketHeader(final long timeStamp) { if (header) { StringBuffer buf = new StringBuffer(dateFormat.format(new Date(timeStamp))); // RFC 3164 says leading space, not leading zero on days 1-9 if (buf.charAt(4) == '0') { buf.setCharAt(4, ' '); } buf.append(getLocalHostname()); buf.append(' '); return buf.toString(); } return ""; }
From source file:com.wabacus.system.dataset.sqldataset.GetDataSetByStoreProcedure.java
private void addRowgroupColsToParams(ReportBean rbean, StringBuffer systemParamsBuf) { AbsListReportDisplayBean alrdbean = (AbsListReportDisplayBean) rbean.getDbean() .getExtendConfigDataForReportType(AbsListReportType.KEY); if (alrdbean != null && alrdbean.getLstRowgroupColsColumn() != null) { StringBuffer rowGroupColsBuf = new StringBuffer(); for (String rowgroupColTmp : alrdbean.getLstRowgroupColsColumn()) { if (rowgroupColTmp != null && !rowgroupColTmp.trim().equals("")) rowGroupColsBuf.append(rowgroupColTmp).append(","); }//from w w w . j av a 2s. c o m if (rowGroupColsBuf.length() > 0) { if (rowGroupColsBuf.charAt(rowGroupColsBuf.length() - 1) == ',') rowGroupColsBuf.deleteCharAt(rowGroupColsBuf.length() - 1); systemParamsBuf.append("{[(<rowgroup_cols:" + rowGroupColsBuf.toString() + ">)]}"); } } }
From source file:org.apache.cocoon.environment.internal.EnvironmentHelper.java
/** * Adds an prefix to the overall stripped off prefix from the request uri *//* www. j a v a2 s . c o m*/ public void changeContext(Source newSource, String newPrefix) throws IOException { final String newContext = newSource.getURI(); if (getLogger().isDebugEnabled()) { getLogger().debug("Changing Cocoon context"); getLogger().debug(" from context(" + this.context + ") and prefix(" + this.prefix + ")"); getLogger().debug(" to context(" + newContext + ") and prefix(" + newPrefix + ")"); } int l = newPrefix.length(); if (l >= 1) { this.lastPrefix = newPrefix; if (this.prefix == null) { this.prefix = ""; } final StringBuffer buffer = new StringBuffer(this.prefix); buffer.append(newPrefix); // check for a slash at the beginning to avoid problems with subsitemaps if (buffer.charAt(buffer.length() - 1) != '/') { buffer.append('/'); this.lastPrefix = this.lastPrefix + '/'; } this.prefix = buffer.toString(); } else { this.lastPrefix = null; } if (SourceUtil.getScheme(this.context).equals("zip")) { // if the resource is zipped into a war file (e.g. Weblogic temp deployment) // FIXME (VG): Is this still required? Better to unify both cases. if (getLogger().isDebugEnabled()) { getLogger().debug("Base context is zip: " + this.context); } org.apache.excalibur.source.Source source = null; try { source = this.resolver.resolveURI(this.context + newContext); this.context = source.getURI(); } finally { this.resolver.release(source); } } else { String sContext; // if we got a absolute context or one with a protocol resolve it if (newContext.charAt(0) == '/') { // context starts with the '/' - absolute file URL sContext = "file:" + newContext; } else if (newContext.indexOf(':') > 1) { // context have ':' - absolute URL sContext = newContext; } else { // context is relative to old one sContext = this.context + '/' + newContext; } // Cut the file name part from context (if present) int i = sContext.lastIndexOf('/'); if (i != -1 && i + 1 < sContext.length()) { sContext = sContext.substring(0, i + 1); } Source source = null; try { source = this.resolver.resolveURI(sContext); this.context = source.getURI(); } finally { this.resolver.release(source); } } if (getLogger().isDebugEnabled()) { getLogger().debug("New context is " + this.context); } }
From source file:Main.java
/** * This method adds underscore in between the words (eg: converts GeneHomolog * to Gene_Homolog)/*from www. j a v a2s . c o m*/ * * @param name */ public static void evaluateString(String name, List<String> options, List<String> words) { if (options == null || words == null) throw new IllegalArgumentException("Options or Words is not initialized"); //remove package name if the name is a class name if (name != null) { int index = name.lastIndexOf("."); name = name.substring(index + 1); } //Set optionSet = new HashSet(); options.add(name); char firstChar = name.charAt(0); firstChar = Character.toUpperCase(firstChar); if (name.indexOf("_") > 0) { String temp = Character.toString(firstChar) + name.substring(1); options.add(temp); } String temp = firstChar + name.substring(1).toLowerCase(); options.add(temp); String evaluatedString = null; ; StringBuffer wholeWords = new StringBuffer(); StringBuffer tempSeparateWord = new StringBuffer(); char[] chars = name.toCharArray(); StringBuffer sb = new StringBuffer(); boolean first = true; int index = 0; for (int i = 0; i < chars.length; i++) { //Character c = new Character(chars[i]); //System.out.println("inside loop i = " +i); if (Character.isUpperCase(chars[i])) { if ((i > 1) && ((i - index) > 1)) { //System.out.println("Inside capital if"); first = false; sb.append("_").append(chars[i]); words.add(tempSeparateWord.toString()); tempSeparateWord = new StringBuffer(); tempSeparateWord.append(chars[i]); wholeWords.append(" ").append(chars[i]); } else { wholeWords.append(chars[i]); tempSeparateWord.append(chars[i]); sb.append(chars[i]); } index = i; } else { if (chars[i] != '_') { sb.append(chars[i]); wholeWords.append(chars[i]); tempSeparateWord.append(chars[i]); } } } //System.out.println("Converted string: "+sb.toString()); //if the string contains "_", then make the first character uppercase if (!first) { char c = Character.toUpperCase(sb.charAt(0)); sb.deleteCharAt(0); sb.insert(0, c); char c1 = Character.toUpperCase(wholeWords.charAt(0)); wholeWords.deleteCharAt(0); wholeWords.insert(0, c1); } options.add(sb.toString()); options.add(wholeWords.toString()); if (words.size() > 0) { /* StringBuffer tmp = (StringBuffer)separateWords.get(0); char c2 = Character.toUpperCase(tmp.charAt(0)); tmp.deleteCharAt(0); tmp.insert(0, c2); separateWords.remove(0); separateWords.add(0, tmp); */ String temp2 = words.get(words.size() - 1).toString(); if (tempSeparateWord != null) { temp = tempSeparateWord.toString(); if (temp2.compareToIgnoreCase(temp) != 0) { words.add(temp); } } } List possibleOptions = new ArrayList(options); options = null;//garbage collection ready //testing for (int i = 0; i < possibleOptions.size(); i++) { System.out.println("options[" + i + "]=" + possibleOptions.get(i)); } for (int i = 0; i < words.size(); i++) { System.out.println("separateWords[" + i + "]=" + words.get(i)); } return; }
From source file:ORG.oclc.oai.server.catalog.AbstractCatalog.java
/** * Convert the requested 'from' parameter to the finest granularity supported by this * repository./* www .j a v a2 s . c o m*/ * * @exception BadArgumentException one or more of the arguments are bad. */ public String toFinestFrom(String from) throws BadArgumentException { if (debug) { System.out.println("AbstractCatalog.toFinestFrom: from=" + from); System.out.println( " target=" + VALID_GRANULARITIES[supportedGranularityOffset]); } if (StringUtils.isEmpty(from)) { return ""; } if (from.length() > VALID_GRANULARITIES[supportedGranularityOffset].length()) { throw new BadArgumentException(); } if (from.length() != VALID_GRANULARITIES[supportedGranularityOffset].length()) { StringBuffer sb = new StringBuffer(from); if (sb.charAt(sb.length() - 1) == 'Z') { sb.setLength(sb.length() - 1); } sb.append(FROM_GRANULARITIES[supportedGranularityOffset].substring(sb.length())); from = sb.toString(); } if (!isValidGranularity(from)) { throw new BadArgumentException(); } return from; }
From source file:stanford.androidlib.xml.XMLTokener.java
/** * Get the text in the CDATA block.//from w ww . j a v a2 s . co m * @return The string up to the ]]>. * @throws JSONException If the ]]> is not found. */ public String nextCDATA() throws JSONException { char c; int i; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); // if (end()) { if (c == '\0') { throw syntaxError("Unclosed CDATA"); } sb.append(c); i = sb.length() - 3; if (i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { sb.setLength(i); return sb.toString(); } } }
From source file:org.jboss.dashboard.commons.text.StringUtil.java
/** * Converts the given string to a Java valid identifier. * * @param str string to process/*from w w w . j a v a2 s . co m*/ * @return A java based identifier. */ public static String toJavaIdentifier(String str) { if (str == null || str.trim().equals("")) return null; StringBuffer buf = new StringBuffer(str); int bufIdx = 0; while (bufIdx < buf.length()) { char c = buf.charAt(bufIdx); // Replace tilded by non-tilded chars. int tilded = TILDED_CHARS.indexOf(c); if (tilded != -1 && tilded < NON_TILDED_CHARS.length()) { buf.deleteCharAt(bufIdx); c = NON_TILDED_CHARS.charAt(tilded); buf.insert(bufIdx++, c); continue; } // Discard special chars and non-valid java identifiers. int special = SPECIAL_CHARS.indexOf(c); if (special != -1 || !Character.isJavaIdentifierPart(c)) { buf.deleteCharAt(bufIdx); continue; } // Adjust buffer index. bufIdx++; } if (buf.length() == 0) return ""; while (buf.length() > 0 && !Character.isJavaIdentifierStart(buf.charAt(0))) buf.deleteCharAt(0); // Avoid reserved java keywords. String javaId = buf.toString(); if (isJavaKeyword(javaId)) { if (javaId.equals("class")) javaId = "clazz"; else javaId = '_' + javaId; } return javaId; }