Java Code Examples for java.io.StringWriter.close()

The following are Jave code examples for showing how to use close() of the java.io.StringWriter class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: parabuild-ci   File: StringConverter.java   View Source Code Vote up 7 votes
/**
 * Using a Reader and a Writer, returns a String from an InputStream.
 */
public static String inputStreamToString(InputStream x,
        int length) throws IOException {

    InputStreamReader in        = new InputStreamReader(x);
    StringWriter      writer    = new StringWriter();
    int               blocksize = 8 * 1024;
    char[]            buffer    = new char[blocksize];

    for (int left = length; left > 0; ) {
        int read = in.read(buffer, 0, left > blocksize ? blocksize
                                                       : left);

        if (read == -1) {
            break;
        }

        writer.write(buffer, 0, read);

        left -= read;
    }

    writer.close();

    return writer.toString();
}
 
Example 2
Project: ditb   File: JSONBean.java   View Source Code Vote up 6 votes
/**
 * Dump out a subset of regionserver mbeans only, not all of them, as json on System.out.
 * @throws MalformedObjectNameException
 * @throws IOException
 */
public static String dumpRegionServerMetrics() throws MalformedObjectNameException, IOException {
  StringWriter sw = new StringWriter(1024 * 100); // Guess this size
  try (PrintWriter writer = new PrintWriter(sw)) {
    JSONBean dumper = new JSONBean();
    try (JSONBean.Writer jsonBeanWriter = dumper.open(writer)) {
      MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
      jsonBeanWriter.write(mbeanServer,
        new ObjectName("java.lang:type=Memory"), null, false);
      jsonBeanWriter.write(mbeanServer,
        new ObjectName("Hadoop:service=HBase,name=RegionServer,sub=IPC"), null, false);
      jsonBeanWriter.write(mbeanServer,
        new ObjectName("Hadoop:service=HBase,name=RegionServer,sub=Replication"), null, false);
      jsonBeanWriter.write(mbeanServer,
        new ObjectName("Hadoop:service=HBase,name=RegionServer,sub=Server"), null, false);
    }
  }
  sw.close();
  return sw.toString();
}
 
Example 3
Project: parabuild-ci   File: StringConverter.java   View Source Code Vote up 6 votes
/**
 * Using a Reader and a Writer, returns a String from an InputStream.
 */
public static String inputStreamToString(InputStream x,
        int length) throws IOException {

    InputStreamReader in        = new InputStreamReader(x);
    StringWriter      writer    = new StringWriter();
    int               blocksize = 8 * 1024;
    char[]            buffer    = new char[blocksize];

    for (int left = length; left > 0; ) {
        int read = in.read(buffer, 0, left > blocksize ? blocksize
                                                       : left);

        if (read == -1) {
            break;
        }

        writer.write(buffer, 0, read);

        left -= read;
    }

    writer.close();

    return writer.toString();
}
 
Example 4
Project: incubator-netbeans   File: TAXUtil.java   View Source Code Vote up 6 votes
public static String treeToString(TreeDocumentRoot doc) throws IOException {

        StringWriter out = new StringWriter();
        TreeStreamResult result = new TreeStreamResult(out);
        TreeWriter writer = result.getWriter(doc);

        try {
            writer.writeDocument();
            return out.toString();
        } catch (TreeException ex) {
            throw new IOException("Cannot read tree " +  ex.getMessage()); // NOI18N

        } finally {
            try {
                out.close();
            } catch (IOException ioex) {
                // do not know
            }
        }

    }
 
Example 5
Project: sstore-soft   File: StringConverter.java   View Source Code Vote up 6 votes
/**
 * Using a Reader and a Writer, returns a String from an InputStream.
 *
 * Method based on Hypersonic Code
 *
 * @param x InputStream to read from
 * @throws IOException
 * @return a Java string
 */
public static String inputStreamToString(InputStream x,
        String encoding) throws IOException {

    InputStreamReader in        = new InputStreamReader(x, encoding);
    StringWriter      writer    = new StringWriter();
    int               blocksize = 8 * 1024;
    char[]            buffer    = new char[blocksize];

    for (;;) {
        int read = in.read(buffer);

        if (read == -1) {
            break;
        }

        writer.write(buffer, 0, read);
    }

    writer.close();

    return writer.toString();
}
 
Example 6
Project: parabuild-ci   File: StringConverter.java   View Source Code Vote up 6 votes
/**
 * Using a Reader and a Writer, returns a String from an InputStream.
 */
public static String inputStreamToString(InputStream x,
        int length) throws IOException {

    InputStreamReader in        = new InputStreamReader(x);
    StringWriter      writer    = new StringWriter();
    int               blocksize = 8 * 1024;
    char[]            buffer    = new char[blocksize];

    for (int left = length; left > 0; ) {
        int read = in.read(buffer, 0, left > blocksize ? blocksize
                                                       : left);

        if (read == -1) {
            break;
        }

        writer.write(buffer, 0, read);

        left -= read;
    }

    writer.close();

    return writer.toString();
}
 
Example 7
Project: jetfuel   File: HttpClient.java   View Source Code Vote up 5 votes
public String downloadString() {
	try {
		StringWriter writer = new StringWriter();
		for (int i = this.responseStream.read(); i >= 0; i = this.responseStream.read())
			writer.write(i);

		String ret = writer.toString();

		writer.close();
		return ret;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 8
Project: xdman   File: AbstractAutoProxyHandler.java   View Source Code Vote up 5 votes
private String getJSFileFromURL(URLConnection paramURLConnection)
		throws Exception {
	// Trace.msgNetPrintln("net.proxy.auto.download.js", new Object[] {
	// paramURLConnection.getURL() });
	try {
		// RemoveCommentReader localRemoveCommentReader = new
		// RemoveCommentReader(new
		// InputStreamReader(paramURLConnection.getInputStream()));
		InputStreamReader localRemoveCommentReader = new InputStreamReader(
				paramURLConnection.getInputStream());
		BufferedReader localBufferedReader = new BufferedReader(
				localRemoveCommentReader);
		StringWriter localStringWriter = new StringWriter();
		char[] arrayOfChar = new char[100];
		int i;
		while ((i = localBufferedReader.read(arrayOfChar)) != -1) {
			localStringWriter.write(arrayOfChar, 0, i);
		}
		localBufferedReader.close();
		localRemoveCommentReader.close();
		localStringWriter.close();
		return localStringWriter.toString();
	} catch (Throwable localThrowable) {
		throw new Exception("Unable to obtain auto proxy file from "
				+ paramURLConnection.getURL(), localThrowable);
	}
}
 
Example 9
Project: googles-monorepo-demo   File: CharSourceTester.java   View Source Code Vote up 5 votes
public void testOpenBufferedStream() throws IOException {
  BufferedReader reader = source.openBufferedStream();

  StringWriter writer = new StringWriter();
  char[] buf = new char[64];
  int read;
  while ((read = reader.read(buf)) != -1) {
    writer.write(buf, 0, read);
  }
  reader.close();
  writer.close();

  assertExpectedString(writer.toString());
}
 
Example 10
Project: guava-mock   File: CharSourceTester.java   View Source Code Vote up 5 votes
public void testOpenBufferedStream() throws IOException {
  BufferedReader reader = source.openBufferedStream();

  StringWriter writer = new StringWriter();
  char[] buf = new char[64];
  int read;
  while ((read = reader.read(buf)) != -1) {
    writer.write(buf, 0, read);
  }
  reader.close();
  writer.close();

  assertExpectedString(writer.toString());
}
 
Example 11
Project: dubbocloud   File: JSON.java   View Source Code Vote up 5 votes
/**
 * json string.
 * 
 * @param obj object.
 * @param properties property name array.
 * @return json string.
 * @throws IOException.
 */
public static String json(Object obj, String[] properties) throws IOException
{
	if( obj == null ) return NULL;
	StringWriter sw = new StringWriter();
	try
	{
		json(obj, properties, sw);
		return sw.getBuffer().toString();
	}
	finally{ sw.close(); }
}
 
Example 12
Project: googles-monorepo-demo   File: CharSourceTester.java   View Source Code Vote up 5 votes
public void testOpenStream() throws IOException {
  Reader reader = source.openStream();

  StringWriter writer = new StringWriter();
  char[] buf = new char[64];
  int read;
  while ((read = reader.read(buf)) != -1) {
    writer.write(buf, 0, read);
  }
  reader.close();
  writer.close();

  assertExpectedString(writer.toString());
}
 
Example 13
Project: parabuild-ci   File: SignedSOAPEnvelope.java   View Source Code Vote up 5 votes
private Document getSOAPEnvelopeAsDocument(SOAPEnvelope env, MessageContext msgContext)
        throws Exception {
    StringWriter writer = new StringWriter();
    SerializationContext serializeContext = new SerializationContext(writer, msgContext);
    env.output(serializeContext);
    writer.close();

    Reader reader = new StringReader(writer.getBuffer().toString());
    Document doc = XMLUtils.newDocument(new InputSource(reader));
    if (doc == null)
        throw new Exception(
                Messages.getMessage("noDoc00", writer.getBuffer().toString()));
    return doc;
}
 
Example 14
Project: dubbocloud   File: IOUtils.java   View Source Code Vote up 5 votes
/**
 * read string.
 * 
 * @param reader Reader instance.
 * @return String.
 * @throws IOException
 */
public static String read(Reader reader) throws IOException
{
	StringWriter writer = new StringWriter();
	try
	{
		write(reader, writer);
		return writer.getBuffer().toString();
	}
	finally{ writer.close(); }
}
 
Example 15
Project: guava-mock   File: CharSourceTester.java   View Source Code Vote up 5 votes
public void testOpenStream() throws IOException {
  Reader reader = source.openStream();

  StringWriter writer = new StringWriter();
  char[] buf = new char[64];
  int read;
  while ((read = reader.read(buf)) != -1) {
    writer.write(buf, 0, read);
  }
  reader.close();
  writer.close();

  assertExpectedString(writer.toString());
}
 
Example 16
Project: neoscada   File: DebianPackageWriter.java   View Source Code Vote up 5 votes
protected ContentProvider createControlContent () throws IOException
{
    this.packageControlFile.set ( BinaryPackageControlFile.Fields.INSTALLED_SIZE, "" + this.installedSize );

    final StringWriter sw = new StringWriter ();
    try ( ControlFileWriter writer = new ControlFileWriter ( sw ) )
    {
        this.packageControlFile.write ( writer );
    }
    sw.close ();

    return new StaticContentProvider ( sw.toString () );
}
 
Example 17
Project: log4j-aws-appenders   File: LogMessage.java   View Source Code Vote up 5 votes
/**
 *  Constructs an instance from a Log4J event, using the specified layout.
 *
 *  @throws RuntimeException if any error occurred during formatting or conversion.
 *          Will include any root cause other than UnsupportedEncodingException.
 */
public LogMessage(LoggingEvent event, Layout layout)
{
    try
    {
        StringWriter out = new StringWriter(1024);
        out.write(layout.format(event));
        if ((event.getThrowableInformation() != null) && layout.ignoresThrowable())
        {
            for (String traceline : event.getThrowableStrRep())
            {
                out.write(traceline);
                out.write(Layout.LINE_SEP);
            }
        }
        out.close();

        this.timestamp = event.getTimeStamp();
        this.message = out.toString();
        this.messageBytes = this.message.getBytes("UTF-8");
    }
    catch (UnsupportedEncodingException e)
    {
        throw new RuntimeException("UnsupportedEncodingException when converting to UTF-8");
    }
    catch (Exception ex)
    {
        throw new RuntimeException("error creating LogMessage", ex);
    }
}
 
Example 18
Project: dubbocloud   File: JSON.java   View Source Code Vote up 5 votes
/**
 * json string.
 * 
 * @param obj object.
 * @return json string.
 * @throws IOException.
 */
public static String json(Object obj) throws IOException
{
	if( obj == null ) return NULL;
	StringWriter sw = new StringWriter();
	try
	{
		json(obj, sw);
		return sw.getBuffer().toString();
	}
	finally{ sw.close(); }
}
 
Example 19
Project: DisCal-Discord-Bot   File: ExceptionHandler.java   View Source Code Vote up 4 votes
public static void sendException(@Nullable IUser author, @Nullable String message, Exception e, Class clazz) {
	if (Main.getSelfUser() != null) {
		IUser bot = Main.getSelfUser();
		EmbedBuilder em = new EmbedBuilder();
		if (bot != null) {
			em.withAuthorIcon(bot.getAvatarURL());
		}
		if (author != null) {
			em.withAuthorName(author.getName());
			em.withThumbnail(author.getAvatarURL());
		}
		em.withColor(239, 15, 0);
		em.withFooterText(clazz.getName());

		String timeStamp = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss").format(Calendar.getInstance().getTime());
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		String error = sw.toString(); // stack trace as a string
		if (error.length() > 1250) {
			error = error.substring(0, 1250);
		}
		pw.close();

		try {
			sw.close();
		} catch (IOException e1) {
			//Can ignore silently...
		}


		em.appendField("Time", timeStamp, true);
		if (e.getMessage() != null) {
			if (e.getMessage().length() > 1024) {
				em.appendField("Exception", e.getMessage().substring(0, 1024), true);
			} else {
				em.appendField("Exception", e.getMessage(), true);
			}
		}
		if (message != null) {
			em.appendField("Message", message, true);
		}

		//Get DisCal guild and channel..
		IGuild guild = Main.client.getGuildByID(266063520112574464L);
		IChannel channel = guild.getChannelByID(302249332244217856L);

		Message.sendMessage(em.build(), "```" + error + "```", channel);
	} else {
		//TODO: Add to log file...
	}
}
 
Example 20
Project: nifi-android-s2s   File: MainActivity.java   View Source Code Vote up 4 votes
private void refresh() {
    final TextView resultView = (TextView) findViewById(R.id.sendResults);
    for (TransactionLogEntry transactionLogEntry : demoAppDB.getLogEntries(lastTimestamp)) {
        StringBuilder stringBuilder = new StringBuilder(LINE_SEPARATOR);
        stringBuilder.append("[");
        stringBuilder.append(simpleDateFormat.format(transactionLogEntry.getCreated()));
        stringBuilder.append("] - ");

        TransactionResult transactionResult = transactionLogEntry.getTransactionResult();
        if (transactionResult != null) {
            if (transactionResult.getFlowFilesSent() < 0) {
                stringBuilder.append(transactionResult.getMessage());
            } else {
                stringBuilder.append("Sent ");
                stringBuilder.append(transactionResult.getFlowFilesSent());
                stringBuilder.append(" flow file(s) and received response \"");
                stringBuilder.append(transactionResult.getResponseCode());
                stringBuilder.append("\"");
            }
        } else {
            IOException ioException = transactionLogEntry.getIoException();
            if (ioException != null) {
                StringWriter stringWriter = new StringWriter();
                try {
                    PrintWriter printWriter = new PrintWriter(stringWriter);
                    try {
                        ioException.printStackTrace(printWriter);
                    } finally {
                        printWriter.close();
                    }
                } finally {
                    try {
                        stringWriter.close();
                    } catch (IOException e) {
                        //Ignore
                    }
                }
                stringBuilder.append(stringWriter);
            } else {
                stringBuilder.append("Error, no transaction result or exception");
            }
        }
        stringBuilder.append(LINE_SEPARATOR);
        lastTimestamp = Math.max(lastTimestamp, transactionLogEntry.getCreated().getTime());
        resultView.append(stringBuilder.toString());
    }
}