Java Code Examples for java.io.StringWriter#getBuffer()

The following examples show how to use java.io.StringWriter#getBuffer() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JSONConvertor.java    From ns4_frame with Apache License 2.0 6 votes vote down vote up
public static Map<String, String> jsonToMap(final String json) {
    try {
        final Map<String, Object> input = objectMapper.readValue(json,
                new TypeReference<HashMap<String, Object>>() {
                });
        final Map<String, String> output = new HashMap<>(input.size());
        final StringWriter writer = new StringWriter();
        final StringBuffer buf = writer.getBuffer();
        for (final Map.Entry<String, Object> entry : input.entrySet()) {
            try (final JsonGenerator gen = new JsonFactory(objectMapper).createGenerator(writer)) {
                gen.writeObject(entry.getValue());
            }
            output.put(entry.getKey(),  StringUtils.stripEnd(StringUtils.stripStart(buf.toString(), "\""),"\""));
            buf.setLength(0);
        }
        return output;
    } catch (IOException e) {
        Log.logError("JSON TO MAP :" + json + " 出现异常:{}", e);
        return null;
    }
}
 
Example 2
Source File: XMLStreamWriterTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test of main method, of class TestXMLStreamWriter.
 */
@Test
public void testWriteComment() {
    try {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><a:html href=\"http://java.sun.com\"><!--This is comment-->java.sun.com</a:html>";
        XMLOutputFactory f = XMLOutputFactory.newInstance();
        // f.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES,
        // Boolean.TRUE);
        StringWriter sw = new StringWriter();
        XMLStreamWriter writer = f.createXMLStreamWriter(sw);
        writer.writeStartDocument("UTF-8", "1.0");
        writer.writeStartElement("a", "html", "http://www.w3.org/TR/REC-html40");
        writer.writeAttribute("href", "http://java.sun.com");
        writer.writeComment("This is comment");
        writer.writeCharacters("java.sun.com");
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
        sw.flush();
        StringBuffer sb = sw.getBuffer();
        System.out.println("sb:" + sb.toString());
        Assert.assertTrue(sb.toString().equals(xml));
    } catch (Exception ex) {
        Assert.fail("Exception: " + ex.getMessage());
    }
}
 
Example 3
Source File: BEncoder.java    From BiglyBT with GNU General Public License v2.0 6 votes vote down vote up
protected StringBuffer
encode(
	Map		map,
	boolean	simple )
{
	StringWriter	writer = new StringWriter(1024);

	setOutputWriter( writer );

	setGenericSimple( simple );

	writeGeneric( map );

	flushOutputStream();

	return( writer.getBuffer());
}
 
Example 4
Source File: ClassSymbols.java    From manifold with Apache License 2.0 5 votes vote down vote up
private Pair<Symbol.ClassSymbol, JCTree.JCCompilationUnit> getClassSymbolForProducedClass( String fqn, BasicJavacTask[] task )
{
  StringWriter errors = new StringWriter();

  // need javac with ManifoldJavaFileManager because the produced class must come from manifold
  task[0] = getJavacTask_ManFileMgr();

  Symbol.ClassSymbol e = IDynamicJdk.instance().getTypeElement( task[0].getContext(), null, fqn );

  if( e != null && e.getSimpleName().contentEquals( ManClassUtil.getShortClassName( fqn ) ) )
  {
    JavacTrees trees = JavacTrees.instance( task[0].getContext() );
    TreePath path = trees.getPath( e );
    if( path != null )
    {
      return new Pair<>( e, (JCTree.JCCompilationUnit)path.getCompilationUnit() );
    }
    else
    {
      // TreePath is only applicable to a source file;
      // if fqn is not a source file, there is no compilation unit available
      return new Pair<>( e, null );
    }
  }

  StringBuffer errorText = errors.getBuffer();
  if( errorText.length() > 0 )
  {
    throw new RuntimeException( "Compile errors:\n" + errorText );
  }

  return null;
}
 
Example 5
Source File: INode.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Dump the subtree starting from this inode.
 * @return a text representation of the tree.
 */
@VisibleForTesting
public final StringBuffer dumpTreeRecursively() {
  final StringWriter out = new StringWriter(); 
  dumpTreeRecursively(new PrintWriter(out, true), new StringBuilder(),
      Snapshot.CURRENT_STATE_ID);
  return out.getBuffer();
}
 
Example 6
Source File: AbstractJSONObject.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Produce a string in double quotes with backslash sequences in all the
 * right places. A backslash will be inserted within </, producing <\/,
 * allowing JSON text to be delivered in HTML. In JSON text, a string
 * cannot contain a control character or an unescaped quote or backslash.
 * @param string A String
 * @return  A String correctly formatted for insertion in a JSON text.
 */
public static String quote(String string) {
    StringWriter sw = new StringWriter();
    synchronized (sw.getBuffer()) {
        try {
            return quote(string, sw).toString();
        } catch (IOException ignored) {
            // will never happen - we are writing to a string writer
            return "";
        }
    }
}
 
Example 7
Source File: TwoColumnOutput.java    From J2ME-Loader with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an instance.
 *
 * @param out {@code non-null;} writer to send final output to
 * @param leftWidth {@code > 0;} width of the left column, in characters
 * @param rightWidth {@code > 0;} width of the right column, in characters
 * @param spacer {@code non-null;} spacer string to sit between the two columns
 */
public TwoColumnOutput(Writer out, int leftWidth, int rightWidth,
                       String spacer) {
    if (out == null) {
        throw new NullPointerException("out == null");
    }

    if (leftWidth < 1) {
        throw new IllegalArgumentException("leftWidth < 1");
    }

    if (rightWidth < 1) {
        throw new IllegalArgumentException("rightWidth < 1");
    }

    if (spacer == null) {
        throw new NullPointerException("spacer == null");
    }

    StringWriter leftWriter = new StringWriter(1000);
    StringWriter rightWriter = new StringWriter(1000);

    this.out = out;
    this.leftWidth = leftWidth;
    this.leftBuf = leftWriter.getBuffer();
    this.rightBuf = rightWriter.getBuffer();
    this.leftColumn = new IndentingWriter(leftWriter, leftWidth);
    this.rightColumn =
        new IndentingWriter(rightWriter, rightWidth, spacer);
}
 
Example 8
Source File: TwoColumnOutput.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructs an instance.
 *
 * @param out {@code non-null;} writer to send final output to
 * @param leftWidth {@code > 0;} width of the left column, in characters
 * @param rightWidth {@code > 0;} width of the right column, in characters
 * @param spacer {@code non-null;} spacer string to sit between the two columns
 */
public TwoColumnOutput(Writer out, int leftWidth, int rightWidth,
                       String spacer) {
    if (out == null) {
        throw new NullPointerException("out == null");
    }

    if (leftWidth < 1) {
        throw new IllegalArgumentException("leftWidth < 1");
    }

    if (rightWidth < 1) {
        throw new IllegalArgumentException("rightWidth < 1");
    }

    if (spacer == null) {
        throw new NullPointerException("spacer == null");
    }

    StringWriter leftWriter = new StringWriter(1000);
    StringWriter rightWriter = new StringWriter(1000);

    this.out = out;
    this.leftWidth = leftWidth;
    this.leftBuf = leftWriter.getBuffer();
    this.rightBuf = rightWriter.getBuffer();
    this.leftColumn = new IndentingWriter(leftWriter, leftWidth);
    this.rightColumn =
        new IndentingWriter(rightWriter, rightWidth, spacer);
}
 
Example 9
Source File: TwoColumnOutput.java    From atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an instance.
 *
 * @param out {@code non-null;} writer to send final output to
 * @param leftWidth {@code > 0;} width of the left column, in characters
 * @param rightWidth {@code > 0;} width of the right column, in characters
 * @param spacer {@code non-null;} spacer string to sit between the two columns
 */
public TwoColumnOutput(Writer out, int leftWidth, int rightWidth,
                       String spacer) {
    if (out == null) {
        throw new NullPointerException("out == null");
    }

    if (leftWidth < 1) {
        throw new IllegalArgumentException("leftWidth < 1");
    }

    if (rightWidth < 1) {
        throw new IllegalArgumentException("rightWidth < 1");
    }

    if (spacer == null) {
        throw new NullPointerException("spacer == null");
    }

    StringWriter leftWriter = new StringWriter(1000);
    StringWriter rightWriter = new StringWriter(1000);

    this.out = out;
    this.leftWidth = leftWidth;
    this.leftBuf = leftWriter.getBuffer();
    this.rightBuf = rightWriter.getBuffer();
    this.leftColumn = new IndentingWriter(leftWriter, leftWidth);
    this.rightColumn =
        new IndentingWriter(rightWriter, rightWidth, spacer);
}
 
Example 10
Source File: TwoColumnOutput.java    From Box with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an instance.
 *
 * @param out {@code non-null;} writer to send final output to
 * @param leftWidth {@code > 0;} width of the left column, in characters
 * @param rightWidth {@code > 0;} width of the right column, in characters
 * @param spacer {@code non-null;} spacer string to sit between the two columns
 */
public TwoColumnOutput(Writer out, int leftWidth, int rightWidth,
                       String spacer) {
    if (out == null) {
        throw new NullPointerException("out == null");
    }

    if (leftWidth < 1) {
        throw new IllegalArgumentException("leftWidth < 1");
    }

    if (rightWidth < 1) {
        throw new IllegalArgumentException("rightWidth < 1");
    }

    if (spacer == null) {
        throw new NullPointerException("spacer == null");
    }

    StringWriter leftWriter = new StringWriter(1000);
    StringWriter rightWriter = new StringWriter(1000);

    this.out = out;
    this.leftWidth = leftWidth;
    this.leftBuf = leftWriter.getBuffer();
    this.rightBuf = rightWriter.getBuffer();
    this.leftColumn = new IndentingWriter(leftWriter, leftWidth);
    this.rightColumn =
        new IndentingWriter(rightWriter, rightWidth, spacer);
}
 
Example 11
Source File: JSONObject.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Produce a string in double quotes with backslash sequences in all the
 * right places. A backslash will be inserted within &lt;/, producing
 * &lt;\/, allowing JSON text to be delivered in HTML. In JSON text, a
 * string cannot contain a control character or an unescaped quote or
 * backslash.
 *
 * @param string
 *            A String
 * @return A String correctly formatted for insertion in a JSON text.
 */
public static String quote(String string) {
    StringWriter sw = new StringWriter();
    synchronized (sw.getBuffer()) {
        try {
            return quote(string, sw).toString();
        } catch (IOException ignored) {
            // will never happen - we are writing to a string writer
            return "";
        }
    }
}
 
Example 12
Source File: JSONObject.java    From KMusic with Apache License 2.0 5 votes vote down vote up
/**
 * Produce a string in double quotes with backslash sequences in all the
 * right places. A backslash will be inserted within </, producing <\/,
 * allowing JSON text to be delivered in HTML. In JSON text, a string cannot
 * contain a control character or an unescaped quote or backslash.
 *
 * @param string
 *            A String
 * @return A String correctly formatted for insertion in a JSON text.
 */
public static String quote(String string) {
    StringWriter sw = new StringWriter();
    synchronized (sw.getBuffer()) {
        try {
            return quote(string, sw).toString();
        } catch (IOException ignored) {
            // will never happen - we are writing to a string writer
            return "";
        }
    }
}
 
Example 13
Source File: MyLogger.java    From SubTitleSearcher with Apache License 2.0 5 votes vote down vote up
/**
 * 记录完善的异常日志信息(包括堆栈信息)
 *
 * @param e
 *                Exception
 */
public static String recordStackTraceMsg(Exception e) {
	StringWriter stringWriter = new StringWriter();
	PrintWriter writer = new PrintWriter(stringWriter);
	e.printStackTrace(writer);
	StringBuffer buffer = stringWriter.getBuffer();
	return buffer.toString();
}
 
Example 14
Source File: TwoColumnOutput.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an instance.
 *
 * @param out {@code non-null;} writer to send final output to
 * @param leftWidth {@code > 0;} width of the left column, in characters
 * @param rightWidth {@code > 0;} width of the right column, in characters
 * @param spacer {@code non-null;} spacer string to sit between the two columns
 */
public TwoColumnOutput(Writer out, int leftWidth, int rightWidth,
                       String spacer) {
    if (out == null) {
        throw new NullPointerException("out == null");
    }

    if (leftWidth < 1) {
        throw new IllegalArgumentException("leftWidth < 1");
    }

    if (rightWidth < 1) {
        throw new IllegalArgumentException("rightWidth < 1");
    }

    if (spacer == null) {
        throw new NullPointerException("spacer == null");
    }

    StringWriter leftWriter = new StringWriter(1000);
    StringWriter rightWriter = new StringWriter(1000);

    this.out = out;
    this.leftWidth = leftWidth;
    this.leftBuf = leftWriter.getBuffer();
    this.rightBuf = rightWriter.getBuffer();
    this.leftColumn = new IndentingWriter(leftWriter, leftWidth);
    this.rightColumn =
        new IndentingWriter(rightWriter, rightWidth, spacer);
}
 
Example 15
Source File: TwoColumnOutput.java    From Box with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an instance.
 *
 * @param out {@code non-null;} writer to send final output to
 * @param leftWidth {@code > 0;} width of the left column, in characters
 * @param rightWidth {@code > 0;} width of the right column, in characters
 * @param spacer {@code non-null;} spacer string to sit between the two columns
 */
public TwoColumnOutput(Writer out, int leftWidth, int rightWidth,
                       String spacer) {
    if (out == null) {
        throw new NullPointerException("out == null");
    }

    if (leftWidth < 1) {
        throw new IllegalArgumentException("leftWidth < 1");
    }

    if (rightWidth < 1) {
        throw new IllegalArgumentException("rightWidth < 1");
    }

    if (spacer == null) {
        throw new NullPointerException("spacer == null");
    }

    StringWriter leftWriter = new StringWriter(1000);
    StringWriter rightWriter = new StringWriter(1000);

    this.out = out;
    this.leftWidth = leftWidth;
    this.leftBuf = leftWriter.getBuffer();
    this.rightBuf = rightWriter.getBuffer();
    this.leftColumn = new IndentingWriter(leftWriter, leftWidth);
    this.rightColumn =
        new IndentingWriter(rightWriter, rightWidth, spacer);
}
 
Example 16
Source File: MyLogger.java    From SubTitleSearcher with Apache License 2.0 5 votes vote down vote up
/**
 * 记录完善的异常日志信息(包括堆栈信息)
 *
 * @param e
 *                Exception
 */
public static String recordStackTraceMsg(Exception e) {
	StringWriter stringWriter = new StringWriter();
	PrintWriter writer = new PrintWriter(stringWriter);
	e.printStackTrace(writer);
	StringBuffer buffer = stringWriter.getBuffer();
	return buffer.toString();
}
 
Example 17
Source File: FileHandlerV1.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private void handlePatchContents(HttpServletRequest request, BufferedReader requestReader, HttpServletResponse response, IFileStore file)
		throws IOException, CoreException, NoSuchAlgorithmException, JSONException, ServletException {
	JSONObject changes = OrionServlet.readJSONRequest(request);
	// read file to memory
	Reader fileReader = new InputStreamReader(file.openInputStream(EFS.NONE, null));
	StringWriter oldFile = new StringWriter();
	IOUtilities.pipe(fileReader, oldFile, true, false);
	StringBuffer oldContents = oldFile.getBuffer();
	// Remove the BOM character if it exists
	if (oldContents.length() > 0) {
		char firstChar = oldContents.charAt(0);
		if (firstChar == '\uFEFF' || firstChar == '\uFFFE') {
			oldContents.replace(0, 1, "");
		}
	}
	JSONArray changeList = changes.getJSONArray("diff");
	for (int i = 0; i < changeList.length(); i++) {
		JSONObject change = changeList.getJSONObject(i);
		long start = change.getLong("start");
		long end = change.getLong("end");
		String text = change.getString("text");
		oldContents.replace((int) start, (int) end, text);
	}

	String newContents = oldContents.toString();
	boolean failed = false;
	if (changes.has("contents")) {
		String contents = changes.getString("contents");
		if (!newContents.equals(contents)) {
			failed = true;
			newContents = contents;
		}
	}
	Writer fileWriter = new OutputStreamWriter(file.openOutputStream(EFS.NONE, null), "UTF-8");
	IOUtilities.pipe(new StringReader(newContents), fileWriter, false, true);
	if (failed) {
		statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_ACCEPTABLE,
				"Bad File Diffs. Please paste this content in a bug report: \u00A0\u00A0 	" + changes.toString(), null));
		return;
	}

	// return metadata with the new Etag
	handleGetMetadata(request, response, file);
}
 
Example 18
Source File: JSONArray.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Make a pretty-printed JSON text of this JSONArray.
 * 
 * <p>If <code>indentFactor > 0</code> and the {@link JSONArray} has only
 * one element, then the array will be output on a single line:
 * <pre>{@code [1]}</pre>
 * 
 * <p>If an array has 2 or more elements, then it will be output across
 * multiple lines: <pre>{@code
 * [
 * 1,
 * "value 2",
 * 3
 * ]
 * }</pre>
 * <p><b>
 * Warning: This method assumes that the data structure is acyclical.
 * </b>
 * 
 * @param indentFactor
 *            The number of spaces to add to each level of indentation.
 * @return a printable, displayable, transmittable representation of the
 *         object, beginning with <code>[</code>&nbsp;<small>(left
 *         bracket)</small> and ending with <code>]</code>
 *         &nbsp;<small>(right bracket)</small>.
 * @throws JSONException
 */
public String toString(int indentFactor) throws JSONException {
    StringWriter sw = new StringWriter();
    synchronized (sw.getBuffer()) {
        return this.write(sw, indentFactor, 0).toString();
    }
}
 
Example 19
Source File: JSONArray.java    From KMusic with Apache License 2.0 3 votes vote down vote up
/**
 * Make a pretty-printed JSON text of this JSONArray.
 * 
 * <p>If <code>indentFactor > 0</code> and the {@link JSONArray} has only
 * one element, then the array will be output on a single line:
 * <pre>{@code [1]}</pre>
 * 
 * <p>If an array has 2 or more elements, then it will be output across
 * multiple lines: <pre>{@code
 * [
 * 1,
 * "value 2",
 * 3
 * ]
 * }</pre>
 * <p><b>
 * Warning: This method assumes that the data structure is acyclical.
 * </b>
 * 
 * @param indentFactor
 *            The number of spaces to add to each level of indentation.
 * @return a printable, displayable, transmittable representation of the
 *         object, beginning with <code>[</code>&nbsp;<small>(left
 *         bracket)</small> and ending with <code>]</code>
 *         &nbsp;<small>(right bracket)</small>.
 * @throws JSONException
 */
public String toString(int indentFactor) throws JSONException {
    StringWriter sw = new StringWriter();
    synchronized (sw.getBuffer()) {
        return this.write(sw, indentFactor, 0).toString();
    }
}
 
Example 20
Source File: JSONObject.java    From KMusic with Apache License 2.0 3 votes vote down vote up
/**
 * Make a pretty-printed JSON text of this JSONObject.
 * 
 * <p>If <code>indentFactor > 0</code> and the {@link JSONObject}
 * has only one key, then the object will be output on a single line:
 * <pre>{@code {"key": 1}}</pre>
 * 
 * <p>If an object has 2 or more keys, then it will be output across
 * multiple lines: <code><pre>{
 *  "key1": 1,
 *  "key2": "value 2",
 *  "key3": 3
 * }</pre></code>
 * <p><b>
 * Warning: This method assumes that the data structure is acyclical.
 * </b>
 *
 * @param indentFactor
 *            The number of spaces to add to each level of indentation.
 * @return a printable, displayable, portable, transmittable representation
 *         of the object, beginning with <code>{</code>&nbsp;<small>(left
 *         brace)</small> and ending with <code>}</code>&nbsp;<small>(right
 *         brace)</small>.
 * @throws JSONException
 *             If the object contains an invalid number.
 */
public String toString(int indentFactor) throws JSONException {
    StringWriter w = new StringWriter();
    synchronized (w.getBuffer()) {
        return this.write(w, indentFactor, 0).toString();
    }
}