List of usage examples for java.lang StringBuffer getChars
@Override public synchronized void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
From source file:edu.lternet.pasta.portal.Harvester.java
/** * Reads character data from the <code>StringBuffer</code> provided, and * writes it to the <code>Writer</code> provided, using a buffered write. * * @param buffer <code>StringBuffer</code> whose contents are * to be written to the <code>Writer</code> * * @param writer <code>java.io.Writer</code> where contents * of StringBuffer are to be written * * @param closeWhenFinished <code>boolean</code> value to indicate * whether Reader should be closed when reading * finished * * @return <code>StringBuffer</code> containing * characters read from the <code>Reader</code> * * @throws IOException if there are problems accessing or using the Writer. *//*from ww w . jav a2 s .c om*/ public void writeToWriter(StringBuffer buffer, Writer writer, boolean closeWhenFinished) throws IOException { if (writer == null) { throw new IOException("writeToWriter(): Writer is null"); } char[] bufferChars = new char[buffer.length()]; buffer.getChars(0, buffer.length(), bufferChars, 0); try { writer.write(bufferChars); writer.flush(); } catch (IOException ioe) { throw ioe; } finally { if (closeWhenFinished) { try { if (writer != null) writer.close(); } catch (IOException ce) { ce.printStackTrace(); } } } }
From source file:org.apache.cocoon.components.language.programming.java.EclipseJavaCompiler.java
public boolean compile() throws IOException { final String targetClassName = makeClassName(sourceFile); final ClassLoader classLoader = ClassUtils.getClassLoader(); String[] fileNames = new String[] { sourceFile }; String[] classNames = new String[] { targetClassName }; class CompilationUnit implements ICompilationUnit { String className;//w w w .ja v a 2s. c om String sourceFile; CompilationUnit(String sourceFile, String className) { this.className = className; this.sourceFile = sourceFile; } public char[] getFileName() { return className.toCharArray(); } public char[] getContents() { char[] result = null; FileReader fr = null; try { fr = new FileReader(sourceFile); Reader reader = new BufferedReader(fr); if (reader != null) { char[] chars = new char[8192]; StringBuffer buf = new StringBuffer(); int count; while ((count = reader.read(chars, 0, chars.length)) > 0) { buf.append(chars, 0, count); } result = new char[buf.length()]; buf.getChars(0, result.length, result, 0); } } catch (IOException e) { handleError(className, -1, -1, e.getMessage()); } return result; } public char[] getMainTypeName() { int dot = className.lastIndexOf('.'); if (dot > 0) { return className.substring(dot + 1).toCharArray(); } return className.toCharArray(); } public char[][] getPackageName() { StringTokenizer izer = new StringTokenizer(className, "."); char[][] result = new char[izer.countTokens() - 1][]; for (int i = 0; i < result.length; i++) { String tok = izer.nextToken(); result[i] = tok.toCharArray(); } return result; } } final INameEnvironment env = new INameEnvironment() { public NameEnvironmentAnswer findType(char[][] compoundTypeName) { StringBuffer result = new StringBuffer(); for (int i = 0; i < compoundTypeName.length; i++) { if (i > 0) { result.append("."); } result.append(compoundTypeName[i]); } return findType(result.toString()); } public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { StringBuffer result = new StringBuffer(); for (int i = 0; i < packageName.length; i++) { if (i > 0) { result.append("."); } result.append(packageName[i]); } result.append("."); result.append(typeName); return findType(result.toString()); } private NameEnvironmentAnswer findType(String className) { try { if (className.equals(targetClassName)) { ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className); return new NameEnvironmentAnswer(compilationUnit); } String resourceName = className.replace('.', '/') + ".class"; InputStream is = classLoader.getResourceAsStream(resourceName); if (is != null) { byte[] classBytes; byte[] buf = new byte[8192]; ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length); int count; while ((count = is.read(buf, 0, buf.length)) > 0) { baos.write(buf, 0, count); } baos.flush(); classBytes = baos.toByteArray(); char[] fileName = className.toCharArray(); ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true); return new NameEnvironmentAnswer(classFileReader); } } catch (IOException exc) { handleError(className, -1, -1, exc.getMessage()); } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) { handleError(className, -1, -1, exc.getMessage()); } return null; } private boolean isPackage(String result) { if (result.equals(targetClassName)) { return false; } String resourceName = result.replace('.', '/') + ".class"; InputStream is = classLoader.getResourceAsStream(resourceName); return is == null; } public boolean isPackage(char[][] parentPackageName, char[] packageName) { StringBuffer result = new StringBuffer(); if (parentPackageName != null) { for (int i = 0; i < parentPackageName.length; i++) { if (i > 0) { result.append("."); } result.append(parentPackageName[i]); } } String str = new String(packageName); if (Character.isUpperCase(str.charAt(0)) && !isPackage(result.toString())) { return false; } result.append("."); result.append(str); return isPackage(result.toString()); } public void cleanup() { // EMPTY } }; final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems(); final Map settings = new HashMap(9); settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE); settings.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE); if (sourceEncoding != null) { settings.put(CompilerOptions.OPTION_Encoding, sourceEncoding); } if (debug) { settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } // Set the sourceCodeVersion switch (this.compilerComplianceLevel) { case 150: settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5); break; case 140: settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4); break; default: settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3); } // Set the target platform switch (SystemUtils.JAVA_VERSION_INT) { case 150: settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); break; case 140: settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); break; default: settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3); } final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); final ICompilerRequestor requestor = new ICompilerRequestor() { public void acceptResult(CompilationResult result) { try { if (result.hasErrors()) { IProblem[] errors = result.getErrors(); for (int i = 0; i < errors.length; i++) { IProblem error = errors[i]; String name = new String(errors[i].getOriginatingFileName()); handleError(name, error.getSourceLineNumber(), -1, error.getMessage()); } } else { ClassFile[] classFiles = result.getClassFiles(); for (int i = 0; i < classFiles.length; i++) { ClassFile classFile = classFiles[i]; char[][] compoundName = classFile.getCompoundName(); StringBuffer className = new StringBuffer(); for (int j = 0; j < compoundName.length; j++) { if (j > 0) { className.append("."); } className.append(compoundName[j]); } byte[] bytes = classFile.getBytes(); String outFile = destDir + "/" + className.toString().replace('.', '/') + ".class"; FileOutputStream fout = new FileOutputStream(outFile); BufferedOutputStream bos = new BufferedOutputStream(fout); bos.write(bytes); bos.close(); } } } catch (IOException exc) { exc.printStackTrace(); } } }; ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length]; for (int i = 0; i < compilationUnits.length; i++) { String className = classNames[i]; compilationUnits[i] = new CompilationUnit(fileNames[i], className); } Compiler compiler = new Compiler(env, policy, settings, requestor, problemFactory); compiler.compile(compilationUnits); return errors.size() == 0; }
From source file:org.tinygroup.jspengine.compiler.JDTJavaCompiler.java
public JavacErrorDetail[] compile(final String targetClassName, final Node.Nodes pageNodes) throws JasperException { final String sourceFile = ctxt.getServletJavaFileName(); final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath(); String packageName = ctxt.getServletPackageName(); final ClassLoader classLoader = ctxt.getJspLoader(); String[] fileNames = new String[] { sourceFile }; String[] classNames = new String[] { targetClassName }; final ArrayList<JavacErrorDetail> problemList = new ArrayList<JavacErrorDetail>(); class CompilationUnit implements ICompilationUnit { String className;// w w w . j ava 2 s . c om String sourceFile; CompilationUnit(String sourceFile, String className) { this.className = className; this.sourceFile = sourceFile; } public char[] getFileName() { return className.toCharArray(); } public char[] getContents() { char[] result = null; Reader reader = null; try { InputStreamReader isReader = new InputStreamReader(new FileInputStream(sourceFile), ctxt.getOptions().getJavaEncoding()); reader = new BufferedReader(isReader); if (reader != null) { char[] chars = new char[8192]; StringBuffer buf = new StringBuffer(); int count; while ((count = reader.read(chars, 0, chars.length)) > 0) { buf.append(chars, 0, count); } result = new char[buf.length()]; buf.getChars(0, result.length, result, 0); } } catch (IOException e) { log.error("Compilation error", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { // Ignore } } } return result; } public char[] getMainTypeName() { int dot = className.lastIndexOf('.'); if (dot > 0) { return className.substring(dot + 1).toCharArray(); } return className.toCharArray(); } public char[][] getPackageName() { StringTokenizer izer = new StringTokenizer(className, "."); char[][] result = new char[izer.countTokens() - 1][]; for (int i = 0; i < result.length; i++) { String tok = izer.nextToken(); result[i] = tok.toCharArray(); } return result; } } final INameEnvironment env = new INameEnvironment() { public NameEnvironmentAnswer findType(char[][] compoundTypeName) { String result = ""; String sep = ""; for (int i = 0; i < compoundTypeName.length; i++) { result += sep; result += new String(compoundTypeName[i]); sep = "."; } return findType(result); } public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { String result = ""; String sep = ""; for (int i = 0; i < packageName.length; i++) { result += sep; result += new String(packageName[i]); sep = "."; } result += sep; result += new String(typeName); return findType(result); } private NameEnvironmentAnswer findType(String className) { InputStream is = null; try { if (className.equals(targetClassName)) { ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className); return new NameEnvironmentAnswer(compilationUnit, null); } String resourceName = className.replace('.', '/') + ".class"; is = classLoader.getResourceAsStream(resourceName); if (is != null) { byte[] classBytes; byte[] buf = new byte[8192]; ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length); int count; while ((count = is.read(buf, 0, buf.length)) > 0) { baos.write(buf, 0, count); } baos.flush(); classBytes = baos.toByteArray(); char[] fileName = className.toCharArray(); ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true); return new NameEnvironmentAnswer(classFileReader, null); } } catch (IOException exc) { log.error("Compilation error", exc); } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) { log.error("Compilation error", exc); } finally { if (is != null) { try { is.close(); } catch (IOException exc) { // Ignore } } } return null; } private boolean isPackage(String result) { if (result.equals(targetClassName)) { return false; } String resourceName = result.replace('.', '/') + ".class"; InputStream is = classLoader.getResourceAsStream(resourceName); return is == null; } public boolean isPackage(char[][] parentPackageName, char[] packageName) { String result = ""; String sep = ""; if (parentPackageName != null) { for (int i = 0; i < parentPackageName.length; i++) { result += sep; String str = new String(parentPackageName[i]); result += str; sep = "."; } } String str = new String(packageName); if (Character.isUpperCase(str.charAt(0))) { if (!isPackage(result)) { return false; } } result += sep; result += str; return isPackage(result); } public void cleanup() { } }; final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems(); if (ctxt.getOptions().getJavaEncoding() != null) { settings.put(CompilerOptions.OPTION_Encoding, ctxt.getOptions().getJavaEncoding()); } final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); final ICompilerRequestor requestor = new ICompilerRequestor() { public void acceptResult(CompilationResult result) { try { if (result.hasProblems()) { IProblem[] problems = safeGetProblems(result); for (int i = 0; i < problems.length; i++) { IProblem problem = problems[i]; if (problem.isError()) { String name = new String(problems[i].getOriginatingFileName()); try { problemList.add(ErrorDispatcher.createJavacError(name, pageNodes, new StringBuffer(problem.getMessage()), problem.getSourceLineNumber())); } catch (JasperException e) { log.error("Error visiting node", e); } } } } if (problemList.isEmpty()) { ClassFile[] classFiles = result.getClassFiles(); for (int i = 0; i < classFiles.length; i++) { ClassFile classFile = classFiles[i]; char[][] compoundName = classFile.getCompoundName(); String className = ""; String sep = ""; for (int j = 0; j < compoundName.length; j++) { className += sep; className += new String(compoundName[j]); sep = "."; } byte[] bytes = classFile.getBytes(); String outFile = outputDir + "/" + className.replace('.', '/') + ".class"; FileOutputStream fout = new FileOutputStream(outFile); BufferedOutputStream bos = new BufferedOutputStream(fout); bos.write(bytes); bos.close(); } } } catch (IOException exc) { log.error("Compilation error", exc); } } }; ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length]; for (int i = 0; i < compilationUnits.length; i++) { compilationUnits[i] = new CompilationUnit(fileNames[i], classNames[i]); } Compiler compiler = new Compiler(env, policy, settings, requestor, problemFactory); compiler.compile(compilationUnits); if (problemList.isEmpty()) { return null; } return problemList.toArray(new JavacErrorDetail[] {}); }
From source file:org.apache.tapestry.engine.DefaultTemplateSource.java
/** * Reads a Stream into memory as an array of characters. * **///from w w w .j av a 2s . c o m private char[] readTemplateStream(InputStream stream, String encoding) throws IOException { char[] charBuffer = new char[BUFFER_SIZE]; StringBuffer buffer = new StringBuffer(); InputStreamReader reader; if (encoding != null) reader = new InputStreamReader(new BufferedInputStream(stream), encoding); else reader = new InputStreamReader(new BufferedInputStream(stream)); try { while (true) { int charsRead = reader.read(charBuffer, 0, BUFFER_SIZE); if (charsRead <= 0) break; buffer.append(charBuffer, 0, charsRead); } } finally { reader.close(); } // OK, now reuse the charBuffer variable to // produce the final result. int length = buffer.length(); charBuffer = new char[length]; // Copy the character out of the StringBuffer and into the // array. buffer.getChars(0, length, charBuffer, 0); return charBuffer; }
From source file:org.apache.fop.render.rtf.rtflib.rtfdoc.RtfExternalGraphic.java
/** * Writes the RTF content to m_writer - this one throws ExternalGraphicExceptions * * @exception IOException On error// ww w. ja v a 2s.c o m */ protected void writeRtfContentWithException() throws IOException { if (writer == null) { return; } if (url == null && imagedata == null) { throw new ExternalGraphicException("No image data is available (neither URL, nor in-memory)"); } String linkToRoot = System.getProperty("jfor_link_to_root"); if (url != null && linkToRoot != null) { writer.write("{\\field {\\* \\fldinst { INCLUDEPICTURE \""); writer.write(linkToRoot); File urlFile = new File(url.getFile()); writer.write(urlFile.getName()); writer.write("\" \\\\* MERGEFORMAT \\\\d }}}"); return; } // getRtfFile ().getLog ().logInfo ("Writing image '" + url + "'."); if (imagedata == null) { try { final InputStream in = url.openStream(); try { imagedata = IOUtils.toByteArray(url.openStream()); } finally { IOUtils.closeQuietly(in); } } catch (Exception e) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + url + "' (" + e + ")"); } } if (imagedata == null) { return; } // Determine image file format String file = (url != null ? url.getFile() : "<unknown>"); imageformat = FormatBase.determineFormat(imagedata); if (imageformat != null) { imageformat = imageformat.convert(imageformat, imagedata); } if (imageformat == null || imageformat.getType() == ImageConstants.I_NOT_SUPPORTED || "".equals(imageformat.getRtfTag())) { throw new ExternalGraphicException("The tag <fo:external-graphic> " + "does not support " + file.substring(file.lastIndexOf(".") + 1) + " - image type."); } // Writes the beginning of the rtf image writeGroupMark(true); writeStarControlWord("shppict"); writeGroupMark(true); writeControlWord("pict"); StringBuffer buf = new StringBuffer(imagedata.length * 3); writeControlWord(imageformat.getRtfTag()); computeImageSize(); writeSizeInfo(); writeAttributes(getRtfAttributes(), null); for (int i = 0; i < imagedata.length; i++) { int iData = imagedata[i]; // Make positive byte if (iData < 0) { iData += 256; } if (iData < 16) { // Set leading zero and append buf.append('0'); } buf.append(Integer.toHexString(iData)); } int len = buf.length(); char[] chars = new char[len]; buf.getChars(0, len, chars, 0); writer.write(chars); // Writes the end of RTF image writeGroupMark(false); writeGroupMark(false); }
From source file:FastStringBuffer.java
/** * Append the contents of a StringBuffer onto the FastStringBuffer, * growing the storage if necessary.//from w w w . j ava 2s .c om * <p> * NOTE THAT after calling append(), previously obtained * references to m_array[] may no longer be valid. * * @param value StringBuffer whose contents are to be appended. */ public final void append(StringBuffer value) { if (value == null) return; int strlen = value.length(); if (0 == strlen) return; int copyfrom = 0; char[] chunk = m_array[m_lastChunk]; int available = m_chunkSize - m_firstFree; // Repeat while data remains to be copied while (strlen > 0) { // Copy what fits if (available > strlen) available = strlen; value.getChars(copyfrom, copyfrom + available, m_array[m_lastChunk], m_firstFree); strlen -= available; copyfrom += available; // If there's more left, allocate another chunk and continue if (strlen > 0) { // Extend array? int i = m_array.length; if (m_lastChunk + 1 == i) { char[][] newarray = new char[i + 16][]; System.arraycopy(m_array, 0, newarray, 0, i); m_array = newarray; } // Advance one chunk chunk = m_array[++m_lastChunk]; if (chunk == null) { // Hierarchical encapsulation if (m_lastChunk == 1 << m_rebundleBits && m_chunkBits < m_maxChunkBits) { // Should do all the work of both encapsulating // existing data and establishing new sizes/offsets m_innerFSB = new FastStringBuffer(this); } // Add a chunk. chunk = m_array[m_lastChunk] = new char[m_chunkSize]; } available = m_chunkSize; m_firstFree = 0; } } // Adjust the insert point in the last chunk, when we've reached it. m_firstFree += available; }
From source file:it.d4nguard.rgrpg.util.StringCompiler.java
/** * Appends a string buffer to this string builder. * Appending null will call {@link #appendNull()}. * /*from w ww . j a v a 2 s .com*/ * @param str * the string buffer to append * @return this, to enable chaining */ public StringCompiler append(StringBuffer str) { preliminars(); if (str == null) { return appendNull(); } int strLen = str.length(); if (strLen > 0) { int len = length(); ensureCapacity(len + strLen); str.getChars(0, strLen, buffer, len); size += strLen; } return this; }
From source file:it.d4nguard.rgrpg.util.StringCompiler.java
/** * Appends part of a string buffer to this string builder. * Appending null will call {@link #appendNull()}. * /*from w ww .j a va 2 s .c o m*/ * @param str * the string to append * @param startIndex * the start index, inclusive, must be valid * @param length * the length to append, must be valid * @return this, to enable chaining */ public StringCompiler append(StringBuffer str, int startIndex, int length) { preliminars(); if (str == null) { return appendNull(); } if (startIndex < 0 || startIndex > str.length()) { throw new StringIndexOutOfBoundsException("startIndex must be valid"); } if (length < 0 || (startIndex + length) > str.length()) { throw new StringIndexOutOfBoundsException("length must be valid"); } if (length > 0) { int len = length(); ensureCapacity(len + length); str.getChars(startIndex, startIndex + length, buffer, len); size += length; } return this; }
From source file:cgeo.geocaching.cgBase.java
/** * Replace the characters \n, \r and \t with a space * * @param buffer//from w ww . j a va 2 s. com * The data */ public static void replaceWhitespace(final StringBuffer buffer) { final int length = buffer.length(); final char[] chars = new char[length]; buffer.getChars(0, length, chars, 0); int resultSize = 0; boolean lastWasWhitespace = false; for (char c : chars) { if (c == ' ' || c == '\n' || c == '\r' || c == '\t') { if (!lastWasWhitespace) { chars[resultSize++] = ' '; } lastWasWhitespace = true; } else { chars[resultSize++] = c; lastWasWhitespace = false; } } buffer.setLength(0); buffer.append(chars); }
From source file:carnero.cgeo.cgBase.java
private String replaceWhitespace(final StringBuffer buffer) { final int length = buffer.length(); final char[] bytes = new char[length]; buffer.getChars(0, length, bytes, 0); int resultSize = 0; boolean lastWasWhitespace = false; for (int i = 0; i < length; i++) { char c = bytes[i]; if (c == ' ' || c == '\n' || c == '\r' || c == '\t') { if (!lastWasWhitespace) { bytes[resultSize++] = ' '; }//ww w . j a va2 s . co m lastWasWhitespace = true; } else { bytes[resultSize++] = c; lastWasWhitespace = false; } } return new String(bytes, 0, resultSize); }