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:com.qatickets.service.VelocityTemplatesService.java

public String processTemplate(String template, Map<String, Object> ctx) {

    try {/*from  w w w.  ja va  2 s .c  o m*/

        final Writer w = new StringWriter();

        Velocity.evaluate(this.convert(ctx), w, template, new StringReader(template));

        return w.toString();

    } catch (Exception ex) {
        log.error("Error processing template file: " + template, ex);
    }

    return StringHelper.EMPTY;
}

From source file:cn.sharesdk.analysis.util.CrashHandler.java

private String getErrorInfo(Throwable arg1) {
    Writer writer = new StringWriter();
    PrintWriter pw = new PrintWriter(writer);
    arg1.printStackTrace(pw);/* w ww .  j  a  va  2s .  com*/
    pw.close();
    String error = writer.toString();
    return error;
}

From source file:com.betfair.cougar.core.api.fault.FaultDetail.java

public String getStackTrace() {
    if (exception == null) {
        return "";
    }//from  ww w  . ja va 2 s. c o m
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    exception.printStackTrace(printWriter);
    return result.toString();
}

From source file:eu.openminted.toolkit.elsevier.retriever.JaxbMarshalingTest.java

@Test
public void shouldSerialise() {
    Marshaller marshaller = null;
    try {//  w ww  . jav a  2  s  . co m
        marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        //            marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

        Writer writer = new StringWriter();
        marshaller.marshal(testObject, writer);

        String serialised = writer.toString();
        //            serialised.replaceAll("<\\?xml version=\"1.0\" encoding=\"UTF\\-8\" standalone=\"yes\"\\?>", "");
        String testXmlAsString = FileUtils.readFileToString(new File("src/test/resources/S0140673616313228"),
                "UTF-8");

        System.out.println("serialised test object :\n" + serialised);
        System.out.println("test xml :\n" + testXmlAsString);

        //            Assert.assertEquals(asString, testXmlAsString);
    } catch (PropertyException ex) {
        ex.printStackTrace();
    } catch (JAXBException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:me.mast3rplan.phantombot.HTTPResponse.java

HTTPResponse(String address, String request) throws IOException {

    Socket sock = new Socket(address, 80);
    Writer output = new StringWriter();
    IOUtils.write(request, sock.getOutputStream(), "utf-8");
    IOUtils.copy(sock.getInputStream(), output);
    com.gmt2001.Console.out.println(output.toString());
    Scanner scan = new Scanner(sock.getInputStream());
    String errorLine = scan.nextLine();
    for (String line = scan.nextLine(); !line.equals(""); line = scan.nextLine()) {
        String[] keyval = line.split(":", 2);
        if (keyval.length == 2) {
            values.put(keyval[0], keyval[1].trim());
        } else {//from w w w  .  j  ava  2  s.  c o m
            //?
        }
    }
    while (scan.hasNextLine()) {
        body += scan.nextLine();
    }
    sock.close();

}

From source file:org.gytheio.messaging.marshalling.JsonObjectMarshallerImplTest.java

@Test
public void testTransformationRequestMarshalling() throws Exception {
    PagedSourceOptions sourceOptions = new PagedSourceOptions();
    sourceOptions.setEndPageNumber(EXPECTED_SOURCE_OPTION_VALUE_END_PAGE);

    ImageResizeOptions resizeOptions = new ImageResizeOptions();
    resizeOptions.setWidth(EXPECTED_OPTION_VALUE_WIDTH);
    resizeOptions.setHeight(EXPECTED_OPTION_VALUE_HEIGHT);

    ImageTransformationOptions options = new ImageTransformationOptions();

    options.addSourceOptions(sourceOptions);

    options.setResizeOptions(resizeOptions);

    ContentReference source = new ContentReference(
            "file:/tmp/Alfresco/TempFileContentTransportImpl-88e9011d-6ecf-4a68-8f6c-342d0cd30fee6858578792784676782.mov",
            "video/quicktime");
    ContentReference target = new ContentReference(
            "file:/tmp/Alfresco/TempFileContentTransportImpl-be08c51b-4282-4040-8a58-a1e4cd1df1472999488129563166381.png",
            "image/png");
    TransformationRequest request = new TransformationRequest(Arrays.asList(source), Arrays.asList(target),
            options);//ww w . j av a  2s .co m

    Writer strWriter = new StringWriter();
    objectMapper.writeValue(strWriter, request);
    String requestString = strWriter.toString();

    assertNotNull(requestString);
    //        System.out.println("requestString=" + requestString);
    assertTrue("Marshalled PagedSourceOptions did not contain the expected endPageNumber",
            requestString.contains("\"endPageNumber\":" + EXPECTED_SOURCE_OPTION_VALUE_END_PAGE));

    TransformationRequest unmarshalledRequest = objectMapper.readValue(requestString,
            TransformationRequest.class);

    assertNotNull("Request was null", unmarshalledRequest);
    assertNotNull("Transformation options were null", unmarshalledRequest.getOptions());

    ImageTransformationOptions unmarshalledOptions = (ImageTransformationOptions) unmarshalledRequest
            .getOptions();

    assertNotNull("Transformation resize options were null", unmarshalledOptions.getResizeOptions());

    String unmarshalledImproperlyMessage = "Transformation source options were not unmarshalled properly";
    assertEquals(unmarshalledImproperlyMessage, EXPECTED_OPTION_VALUE_WIDTH,
            unmarshalledOptions.getResizeOptions().getWidth());
    assertEquals(unmarshalledImproperlyMessage, EXPECTED_OPTION_VALUE_HEIGHT,
            unmarshalledOptions.getResizeOptions().getHeight());

    PagedSourceOptions unmarshalledSourceOptions = unmarshalledRequest.getOptions()
            .getSourceOptions(PagedSourceOptions.class);
    assertNotNull("Transformation source options were null", unmarshalledSourceOptions);

    assertEquals(unmarshalledImproperlyMessage, EXPECTED_SOURCE_OPTION_VALUE_END_PAGE,
            unmarshalledSourceOptions.getEndPageNumber());
}

From source file:com.cisco.oss.foundation.tools.simulator.rest.resources.SimulatorNextResponseResource.java

@GET
public Response getSimulator(@PathParam("port") final int port) throws Exception {
    if (!simulatorService.simulatorExists(port)) {
        String msg = "can not retrieve simulator. simulator on port " + port + " doesn't exist";
        logger.error(msg);//from  w  w  w. j  a v  a 2  s. c  o  m
        return Response.status(Status.BAD_REQUEST).entity(msg).build();
    }

    SimulatorResponse simulatorNextResponse = simulatorService.getSimulator(port).getSimulatorNextResponse();

    String simulatorNextResponseStr = "";

    if (simulatorNextResponse != null) {
        Writer strWriter = new StringWriter();
        objectMapper.writeValue(strWriter, simulatorNextResponse);

        simulatorNextResponseStr = strWriter.toString();
    }

    return Response.status(Status.OK).entity(simulatorNextResponseStr).build();
}

From source file:uk.org.funcube.fcdw.server.email.VelocityTemplateEmailSender.java

@Override
public void sendEmailUsingTemplate(final String fromAddress, final String toAddress,
        final String[] bccAddresses, final String subject, final String templateLocation,
        final Map<String, Object> model) {

    final Map<String, Object> augmentedModel = new HashMap<String, Object>(model);
    augmentedModel.put("dateTool", new DateTool());
    augmentedModel.put("numberTool", new NumberTool());
    augmentedModel.put("mathTool", new MathTool());

    final Writer writer = new StringWriter();
    VelocityEngineUtils.mergeTemplate(velocityEngine, templateLocation, augmentedModel, writer);
    final String emailBody = writer.toString();

    final MimeMessagePreparator prep = new MimeMessagePreparator() {
        @Override/*from  w  w  w.  j a va 2 s. com*/
        public void prepare(final MimeMessage mimeMessage) throws Exception {
            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, EMAIL_CONTENT_ENCODING);
            message.setTo(toAddress);
            message.setFrom(fromAddress);
            message.setSubject(subject);
            message.setText(emailBody);

            if (!ArrayUtils.isEmpty(bccAddresses)) {
                message.setBcc(bccAddresses);
            }
        }
    };

    try {
        mailSender.send(prep);
        LOGGER.debug(String.format("Sent %3$s email To: %1$s, Bcc: %2$s", toAddress,
                ArrayUtils.toString(bccAddresses, "None"), templateLocation));
    } catch (final MailException e) {
        LOGGER.error("Could not send email " + subject, e);
        throw e;
    }
}

From source file:eu.eexcess.sourceselection.redde.indexer.trec.topic.TrecTopicTokenizer.java

/**
 * Tokenize trec-topic xml file respecting missing closing xml tags.
 * @param input//from w  w w  .  j ava2 s .  c  om
 * @return
 * @throws IOException
 */
public List<Topic> tokenize(InputStream input) throws IOException {
    Writer writer = new StringWriter();
    IOUtils.copy(input, writer);
    String data = writer.toString();

    Matcher startTopicMatcher = getStartTopicTagMatcher(data);
    Matcher endTopicTagMatcher = getEndTopicTagMatcher(data);

    int processedChars = 0;
    while (startTopicMatcher.find(processedChars)) {
        if (endTopicTagMatcher.find(startTopicMatcher.end())) {
            String topicData = data.substring(processedChars, endTopicTagMatcher.start());
            Matcher startTagMatcher = getStartGenericTagMatcher(topicData);

            while (startTagMatcher.find()) {
                Matcher endTagMatcher = getStartGenericTagMatcher(topicData);
                if (endTagMatcher.find(startTagMatcher.end())) {
                    assignValueToField(startTagMatcher.group(),
                            topicData.substring(startTagMatcher.end(), endTagMatcher.start()));
                } else {
                    // reached last tag in topic
                    assignValueToField(startTagMatcher.group(),
                            topicData.substring(startTagMatcher.end(), topicData.length()));
                }

            }

        } else {
            throw new IllegalArgumentException("expected topic end tag");
        }
        processedChars = endTopicTagMatcher.end();
        topics.add(currentTopic);
        currentTopic = new Topic();
    }
    return topics;
}

From source file:io.kodokojo.service.marathon.MarathonConfigurationStore.java

@Override
public boolean storeSSLKeys(String project, String entityName, SSLKeyPair sslKeyPair) {
    if (isBlank(project)) {
        throw new IllegalArgumentException("project must be defined.");
    }//from   ww  w .j a  v  a2 s.  c om
    if (isBlank(entityName)) {
        throw new IllegalArgumentException("entityName must be defined.");
    }
    if (sslKeyPair == null) {
        throw new IllegalArgumentException("sslKeyPair must be defined.");
    }
    Response response = null;
    try {
        Writer writer = new StringWriter();
        SSLUtils.writeSSLKeyPairPem(sslKeyPair, writer);
        byte[] certificat = writer.toString().getBytes();

        String url = marathonUrl + "/v2/artifacts/ssl/" + project.toLowerCase() + "/" + entityName.toLowerCase()
                + "/" + project.toLowerCase() + "-" + entityName.toLowerCase() + "-server.pem";
        OkHttpClient httpClient = new OkHttpClient();
        RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                .addFormDataPart("file", project + "-" + entityName + "-server.pem",
                        RequestBody.create(MediaType.parse("application/text"), certificat))
                .build();
        Request request = new Request.Builder().url(url).post(requestBody).build();
        response = httpClient.newCall(request).execute();
        int code = response.code();
        if (code > 200 && code < 300) {
            LOGGER.info("Push SSL certificate on marathon url '{}' [content-size={}]", url, certificat.length);
        } else {
            LOGGER.error("Fail to push SSL certificate on marathon url '{}' status code {}. Body response:\n{}",
                    url, code, response.body().string());
        }
        return code > 200 && code < 300;
    } catch (IOException e) {
        LOGGER.error("Unable to store ssl key for project {} and brick {}", project, entityName, e);
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
    return false;
}