Example usage for java.io Writer toString

List of usage examples for java.io Writer toString

Introduction

In this page you can find the example usage for java.io Writer toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.geosdi.geoplatform.connector.server.request.GPPostConnectorRequest.java

@Override
public String getResponseAsString() throws ServerInternalFault, IOException, IllegalParameterFault {
    Writer writer = new StringWriter();
    try {/*from w  ww . j a v a2 s .c  o m*/
        HttpResponse httpResponse = super.securityConnector.secure(this, this.getPostMethod());
        HttpEntity responseEntity = httpResponse.getEntity();

        if (responseEntity != null) {
            InputStream is = responseEntity.getContent();

            char[] buffer = new char[1024];

            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }

            EntityUtils.consume(responseEntity);
        } else {
            throw new ServerInternalFault("Connector Server Error: Connection " + "problem");
        }

    } catch (JAXBException ex) {
        logger.error("\n@@@@@@@@@@@@@@@@@@ JAXBException *** {} ***", ex.getMessage());
        throw new ServerInternalFault("*** JAXBException ***");

    } catch (ClientProtocolException ex) {
        logger.error("\n@@@@@@@@@@@@@@@@@@ ClientProtocolException *** {} ***", ex.getMessage());
        throw new ServerInternalFault("*** ClientProtocolException ***");

    }

    return writer.toString();
}

From source file:com.cloud.bridge.service.controller.s3.S3BucketAction.java

private String streamToString(InputStream is) throws IOException {
    int n = 0;/*www  . j  a v  a 2 s. co m*/

    if (null != is) {
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            while ((n = reader.read(buffer)) != -1)
                writer.write(buffer, 0, n);
        } finally {
            is.close();
        }
        return writer.toString();
    } else
        return null;
}

From source file:hoot.services.command.CommandRunner.java

public CommandResult exec(String[] pCmd, String[] pEnv, Writer pOut, Writer pErr)
        throws IOException, InterruptedException {

    int out = 0;// w  w w .  j a v  a 2  s  .  c o m
    String pCmdString = ArrayUtils.toString(pCmd);
    if (_log.isInfoEnabled())
        _log.info("Executing '" + pCmdString + "' with Environment '" + ArrayUtils.toString(pEnv) + "'");
    StopWatch clock = new StopWatch();
    clock.start();
    try {
        process = Runtime.getRuntime().exec(pCmd, pEnv);
        out = handleProcess(process, pCmdString, pOut, pErr, _outputList, sig_interrupt);
    } finally {
        this.cleanUpProcess();
        clock.stop();
        if (_log.isInfoEnabled())
            _log.info("'" + pCmdString + "' completed in " + clock.getTime() + " ms");
    }
    if (sig_interrupt.getValue() == true) {
        out = -9999;
    }
    CommandResult result = new CommandResult(pCmdString, out, pOut.toString(), pErr.toString());
    return result;
}

From source file:de.shadowhunt.subversion.internal.CommitMessageOperation.java

@Override
protected HttpUriRequest createRequest() {
    final Writer body = new StringBuilderWriter();
    try {/*  ww w .j av a2 s  .c om*/
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("propertyupdate");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        writer.writeStartElement("set");
        writer.writeStartElement("prop");
        writer.setPrefix(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
        writer.writeStartElement(XmlConstants.SUBVERSION_DAV_NAMESPACE, "log");
        writer.writeNamespace(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
        writer.writeCharacters(message);
        writer.writeEndElement(); // log
        writer.writeEndElement(); // prop
        writer.writeEndElement(); // set
        writer.writeEndElement(); // propertyupdate
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    final URI uri = URIUtils.createURI(repository, resource);
    final DavTemplateRequest request = new DavTemplateRequest("PROPPATCH", uri);
    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}

From source file:hoot.services.command.CommandRunner.java

public CommandResult exec(String[] pCmd, File dir, Writer pOut, Writer pErr)
        throws IOException, InterruptedException {
    ProcessBuilder builder = new ProcessBuilder();
    Map<String, String> env = builder.environment();

    int out = 0;/*from ww w.  j  a v a  2 s  .c  om*/
    String pCmdString = ArrayUtils.toString(pCmd);
    logExec(pCmdString, env);

    StopWatch clock = new StopWatch();
    clock.start();
    try {
        process = Runtime.getRuntime().exec(pCmd, null, dir);
        out = handleProcess(process, pCmdString, pOut, pErr, _outputList, sig_interrupt);
    } finally {
        this.cleanUpProcess();
        clock.stop();
        if (_log.isInfoEnabled())
            _log.info("'" + pCmd + "' completed in " + clock.getTime() + " ms");
    }
    if (sig_interrupt.getValue() == true) {
        out = -9999;
    }
    CommandResult result = new CommandResult(pCmdString, out, pOut.toString(), pErr.toString());
    return result;
}

From source file:hoot.services.command.CommandRunner.java

public CommandResult exec(String[] pCmd, String[] pEnv, File dir, Writer pOut, Writer pErr)
        throws IOException, InterruptedException {

    int out = 0;/*from   w  w  w.  j  a v a  2 s. co m*/
    String pCmdString = ArrayUtils.toString(pCmd);
    if (_log.isInfoEnabled())
        _log.info("Executing '" + pCmdString + "' with Environment '" + ArrayUtils.toString(pEnv) + "'");
    StopWatch clock = new StopWatch();
    clock.start();
    try {
        process = Runtime.getRuntime().exec(pCmd, pEnv, dir);
        out = handleProcess(process, pCmdString, pOut, pErr, _outputList, sig_interrupt);
    } finally {
        this.cleanUpProcess();
        clock.stop();
        if (_log.isInfoEnabled())
            _log.info("'" + pCmdString + "' completed in " + clock.getTime() + " ms");
    }

    if (sig_interrupt.getValue() == true) {
        out = -9999;
    }
    CommandResult result = new CommandResult(pCmdString, out, pOut.toString(), pErr.toString());
    return result;
}

From source file:io.datalayer.conf.HierarchicalIniConfigurationTest.java

/**
 * Test of save method, of class {@link HierarchicalINIConfiguration}.
 *//*from   w  ww .  ja va2 s . c o m*/
@Test
public void testSave() throws Exception {
    Writer writer = new StringWriter();
    HierarchicalINIConfiguration instance = new HierarchicalINIConfiguration();
    instance.addProperty("section1.var1", "foo");
    instance.addProperty("section1.var2", "451");
    instance.addProperty("section2.var1", "123.45");
    instance.addProperty("section2.var2", "bar");
    instance.addProperty("section3.var1", "true");
    instance.addProperty("section3.interpolated", "${section3.var1}");
    instance.addProperty("section3.multi", "foo");
    instance.addProperty("section3.multi", "bar");
    instance.save(writer);

    assertEquals("Wrong content of ini file", INI_DATA, writer.toString());
}

From source file:org.apache.pluto.driver.services.container.EventProviderImpl.java

/**
 * Register an event, which should be fired within that request
 * //from w ww  . j av  a2s .  com
 * @param qname
 * @param value
 * @throws {@link IllegalArgumentException}
 */
public void registerToFireEvent(QName qname, Serializable value) throws IllegalArgumentException {
    if (isDeclaredAsPublishingEvent(qname)) {

        if (value != null && !isValueInstanceOfDefinedClass(qname, value))
            throw new IllegalArgumentException("Payload has not the right class");

        try {

            if (value == null) {
                savedEvents.addEvent(new EventImpl(qname, value));
            } else if (!(value instanceof Serializable)) {
                throw new IllegalArgumentException("Object payload must implement Serializable");
            } else {

                Writer out = new StringWriter();

                Class clazz = value.getClass();

                ClassLoader cl = Thread.currentThread().getContextClassLoader();
                try {
                    Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
                    JAXBContext jc = JAXBContext.newInstance(clazz);

                    Marshaller marshaller = jc.createMarshaller();

                    JAXBElement<Serializable> element = new JAXBElement<Serializable>(qname, clazz, value);
                    marshaller.marshal(element, out);
                    // marshaller.marshal(value, out);
                } finally {
                    Thread.currentThread().setContextClassLoader(cl);
                }

                if (out != null) {
                    savedEvents.addEvent(new EventImpl(qname, (Serializable) out.toString()));
                } else {
                    savedEvents.addEvent(new EventImpl(qname, value));
                }
            }
        } catch (JAXBException e) {
            // maybe there is no valid jaxb binding
            // TODO wsrp:eventHandlingFailed
            LOG.error("Event handling failed", e);
        } catch (FactoryConfigurationError e) {
            LOG.warn(e);
        }
    }
}

From source file:com.mobiperf.MeasurementScheduler.java

private String getStackTrace(Throwable error) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    error.printStackTrace(printWriter);/*w  w  w .j a va  2  s  .c  om*/
    return result.toString();
}

From source file:br.ufg.reqweb.components.MailBean.java

public void sendMailToDiscente(final Requerimento requerimento) {
    Thread sender = new Thread() {
        @Override/*from   www.j av a  2 s  .com*/
        public void run() {
            try {
                Configuration templateConf = new Configuration();
                templateConf.setObjectWrapper(new DefaultObjectWrapper());
                templateConf.setDefaultEncoding("UTF-8");
                templateConf.setDirectoryForTemplateLoading(new File(context.getRealPath("/reports/mail")));
                Map objectRoot = new HashMap();
                objectRoot.put("TITULO", LocaleBean.getDefaultMessageBundle().getString("appTitle"));
                objectRoot.put("DISCENTE", LocaleBean.getDefaultMessageBundle().getString("discente"));
                objectRoot.put("REQUERIMENTO", LocaleBean.getDefaultMessageBundle().getString("requerimento"));
                objectRoot.put("STATUS", LocaleBean.getDefaultMessageBundle().getString("status"));
                objectRoot.put("ATENDENTE", LocaleBean.getDefaultMessageBundle().getString("atendente"));
                objectRoot.put("OBSERVACAO", LocaleBean.getDefaultMessageBundle().getString("observacao"));
                objectRoot.put("matricula", requerimento.getDiscente().getMatricula());
                objectRoot.put("discente", requerimento.getDiscente().getNome());
                objectRoot.put("tipoRequerimento", LocaleBean.getDefaultMessageBundle()
                        .getString(requerimento.getTipoRequerimento().getTipo()));
                objectRoot.put("status",
                        LocaleBean.getDefaultMessageBundle().getString(requerimento.getStatus().getStatus()));
                objectRoot.put("atendente", requerimento.getAtendimento().getAtendente().getNome());
                objectRoot.put("observacao", requerimento.getAtendimento().getObservacao());
                URL logo = new File(context.getRealPath("/resources/img/logo-mono-mini.png")).toURI().toURL();
                Template template = templateConf.getTemplate("notificacao_discente.ftl");
                Writer writer = new StringWriter();
                HtmlEmail email = new HtmlEmail();
                String logoId = email.embed(logo, "logo");
                objectRoot.put("logo", logoId);
                template.process(objectRoot, writer);
                email.setHostName(configDao.getValue("mail.mailHost"));
                email.setSmtpPort(Integer.parseInt(configDao.getValue("mail.smtpPort")));
                String mailSender = configDao.getValue("mail.mailSender");
                String user = configDao.getValue("mail.mailUser");
                String password = configDao.getValue("mail.mailPassword");
                boolean useSSL = Boolean.parseBoolean(configDao.getValue("mail.useSSL"));
                email.setAuthenticator(new DefaultAuthenticator(user, password));
                email.setSSLOnConnect(useSSL);
                email.setFrom(mailSender);
                email.addTo(requerimento.getDiscente().getEmail());
                email.setSubject(LocaleBean.getDefaultMessageBundle().getString("subjectMail"));
                email.setHtmlMsg(writer.toString());
                String alternativeMessage = String.format("%s\n%s: %s\n%s: %s\n%s: %s\n%s: %s",
                        LocaleBean.getDefaultMessageBundle().getString("messageMail"),
                        objectRoot.get("REQUERIMENTO"), objectRoot.get("tipoRequerimento"),
                        objectRoot.get("STATUS"), objectRoot.get("status"), objectRoot.get("ATENDENTE"),
                        objectRoot.get("atendente"), objectRoot.get("OBSERVACAO"),
                        objectRoot.get("observacao"));
                email.setTextMsg(alternativeMessage);
                email.send();
                System.out.println(String.format("message to discente:<%s: %s>",
                        requerimento.getDiscente().getNome(), requerimento.getDiscente().getEmail()));
            } catch (EmailException | IOException | TemplateException e) {
                System.out.println("erro ao enviar email");
                System.out.println(e);
            }
        }
    };
    sender.start();
}