Example usage for java.io StringWriter getBuffer

List of usage examples for java.io StringWriter getBuffer

Introduction

In this page you can find the example usage for java.io StringWriter getBuffer.

Prototype

public StringBuffer getBuffer() 

Source Link

Document

Return the string buffer itself.

Usage

From source file:eionet.cr.util.Util.java

/**
 *
 * @param t//from   w  ww. j a v  a  2s .c  o  m
 * @return
 */
public static String getStackTrace(Throwable t) {

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw, true);
    t.printStackTrace(pw);
    return sw.getBuffer().toString();
}

From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java

/**
 * Get data from HTTP POST method./*www .ja va2 s  . c  om*/
 * 
 * This method uses
 * <ul>
 * <li>Connection timeout = 300000 (5 minutes)</li>
 * <li>Socket/Read timeout = 300000 (5 minutes)</li>
 * <li>Socket Read Buffer = 10485760 (10MB) to provide more space to read</li>
 * </ul>
 * -- in case the site is slow
 * 
 * @return
 * @throws MalformedURLException
 * @throws URISyntaxException
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws ClientProtocolException
 * @throws Exception
 */
public static String getPostData(String sourceUrl, String postString) throws MalformedURLException,
        URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException, Exception {
    String result = "";
    URL targetUrl = new URL(sourceUrl);

    /*
     * Create http parameter to set Connection timeout = 300000 Socket/Read
     * timeout = 300000 Socket Read Buffer = 10485760
     */
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 300000);
    HttpConnectionParams.setSocketBufferSize(httpParams, 10485760);
    HttpConnectionParams.setSoTimeout(httpParams, 300000);

    // set the http param to the DefaultHttpClient
    HttpClient httpClient = new DefaultHttpClient(httpParams);

    // create POST method and set the URL and POST data
    HttpPost post = new HttpPost(targetUrl.toURI());
    StringEntity entity = new StringEntity(postString, "UTF-8");
    post.setEntity(entity);
    logger.info("Execute the POST request with all input data");
    // Execute the POST request on the http client to get the response
    HttpResponse response = httpClient.execute(post, new BasicHttpContext());
    if (null != response && response.getStatusLine().getStatusCode() == 200) {
        HttpEntity httpEntity = response.getEntity();
        if (null != httpEntity) {
            long contentLength = httpEntity.getContentLength();
            logger.info("Content length: " + contentLength);
            // no data, if the content length is insufficient
            if (contentLength <= 0) {
                return "";
            }

            // read the response to String
            InputStream responseStream = httpEntity.getContent();
            if (null != responseStream) {
                BufferedReader reader = null;
                StringWriter writer = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(responseStream));
                    writer = new StringWriter();
                    int count = 0;
                    int size = 1024 * 1024;
                    char[] chBuff = new char[size];
                    while ((count = reader.read(chBuff, 0, size)) >= 0) {
                        writer.write(chBuff, 0, count);
                    }
                    result = writer.getBuffer().toString();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw ex;
                } finally {
                    IOUtils.closeQuietly(responseStream);
                    IOUtils.closeQuietly(reader);
                    IOUtils.closeQuietly(writer);
                }
            }
        }
    }
    logger.info("data read complete");
    return result;
}

From source file:de.ingrid.portal.global.UtilsMapServiceManager.java

/**
 * //from   w  w w  .j ava  2 s. c o  m
 * Merge values to gml or map template (velocity macro)
 * 
 * @param path
 * @param coords
 * @param title - title of search hit
 * @param coordClasses - coords classifications
 * @param fileName - mapfile name
 * @param coordClass - null if merge map
 * @param coordType - EPSG code
 * @return string value to create map or gml file
 * @throws ConfigurationException
 * @throws ConfigurationException
 * @throws Exception
 */
public static String mergeTemplateKML(String path, List<HashMap<String, String>> coords, String title,
        String fileName) throws ConfigurationException, Exception {

    StringWriter sw;
    String templatePath;

    VelocityContext context = new VelocityContext();
    context.put("name", title);
    context.put("placemarks", coords);

    sw = new StringWriter();
    templatePath = path;

    try {
        BufferedReader templateReader = new BufferedReader(
                new InputStreamReader(new FileInputStream(templatePath), "UTF8"));
        Velocity.init();
        Velocity.evaluate(context, sw, "TemporaryService", templateReader);
    } catch (Exception e) {
        log.error("failed to merge velocity template: " + templatePath, e);
    }
    String buffer = sw.getBuffer().toString();
    return buffer;
}

From source file:com.uniquesoft.uidl.servlet.UploadServlet.java

/**
 * Simple method to get a string from the exception stack.
 * //from  w  w w .  j  a va  2 s .c  o  m
 * @param e
 * @return string
 */
protected static String stackTraceToString(Throwable e) {
    StringWriter writer = new StringWriter();
    e.printStackTrace(new PrintWriter(writer));
    return writer.getBuffer().toString();
}

From source file:com.technologicaloddity.saha.util.AjaxPageRendererImpl.java

public String render(ModelAndView modelAndView, HttpServletRequest request, HttpServletResponse response) {
    String result = null;//from  ww w . jav  a 2s .  co  m

    StringWriter sout = new StringWriter();
    StringBuffer buffer = sout.getBuffer();

    HttpServletResponse fakeResponse = new SwallowingHttpServletResponse(response, sout,
            response.getCharacterEncoding());

    Locale locale = this.localeResolver.resolveLocale(request);
    fakeResponse.setLocale(locale);

    request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
    try {
        View view = viewResolver.resolveViewName(modelAndView.getViewName(), locale);
        view.render(modelAndView.getModel(), request, fakeResponse);
        result = buffer.toString();
    } catch (Exception e) {
        result = "Ajax render error:" + e.getMessage();
    }
    return result;
}

From source file:controllers.ContestUserController.java

private static String toCsv(List<ContestUser> users) {
    StringWriter sw = new StringWriter();
    CellProcessor[] processors = new CellProcessor[] { new Optional(), new Optional(), new Optional(),
            new Optional(), new Optional(), new Optional(), new Optional(), new Optional(), new Optional() };
    ICsvBeanWriter writer = new CsvBeanWriter(sw, CsvPreference.STANDARD_PREFERENCE);
    try {/* w w  w. j  a  v  a2s.  c o  m*/
        final String[] header = new String[] { "userName", "password", "firstName", "lastName", "middleName",
                "affiliation", "email", "researchArea", "goal" };
        writer.writeHeader(header);
        for (ContestUser user : users) {
            writer.write(user, header, processors);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sw.getBuffer().toString();
}

From source file:com.stratio.explorer.converters.PropertiesToStringConverter.java

/**
 * Transform porperties (key-value) separate by lineSeparator
 * @param properties/*  www .ja v a  2s  . c om*/
 * @return String with values
 */
public String transform(Properties properties) {

    StringWriter writer = new StringWriter();
    properties.list(new PrintWriter(writer));
    return deleteHeaderLine(writer.getBuffer().toString());
}

From source file:com.github.woozoo73.ht.format.XmlFormat.java

public String formatInternal(Invocation invocation) throws Exception {
    JAXBContext jaxbContext = JAXBContext.newInstance(invocation.getClass());
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    StringWriter writer = new StringWriter();
    marshaller.marshal(invocation, writer);

    String xml = writer.getBuffer().toString();

    return xml;/*from  w  w  w.  ja v a2 s  .  c  om*/
}

From source file:org.apache.karaf.shell.tabletest.ShellTableTest.java

private String getString(StringWriter writer) {
    return writer.getBuffer().toString().replace("\r\n", "\n");
}

From source file:de.stklcode.jvault.connector.HTTPVaultConnectorTest.java

/**
 * Retrieve StackTrace from throwable as string
 *
 * @param th the throwable/*from  w  ww . j  a  va  2  s  . com*/
 * @return the stack trace
 */
private static String stackTrace(final Throwable th) {
    StringWriter sw = new StringWriter();
    th.printStackTrace(new PrintWriter(sw, true));
    return sw.getBuffer().toString();
}