Example usage for java.io ByteArrayOutputStream toString

List of usage examples for java.io ByteArrayOutputStream toString

Introduction

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

Prototype

public synchronized String toString() 

Source Link

Document

Converts the buffer's contents into a string decoding bytes using the platform's default character set.

Usage

From source file:net.sourceforge.jukebox.web.SettingsConfiguration.java

/**
 * Handles exceptions.//from  w w  w  .  j ava  2 s  .com
 * @param e Exception
 * @return Error view
 */
@ExceptionHandler(Exception.class)
public final ModelAndView handleErrors(final Exception e) {
    logger.error("Encountered error", e);
    ModelAndView mav = new ModelAndView();
    mav.setViewName("error");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    e.printStackTrace(new PrintWriter(baos, true));
    String stackTrace = baos.toString();
    mav.addObject("errorStackTrace", stackTrace);
    return mav;
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.server.serialization.CatalogRequestBuilderTest.java

private String getMultipartEntityString(HttpPost httpPost) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream((int) httpPost.getEntity().getContentLength());
    httpPost.getEntity().writeTo(out);//from   w w w . j a  v a2 s .  c o  m
    return out.toString();
}

From source file:no.difi.sdp.client.internal.SDPBuilderManifestTest.java

@Test
public void build_expected_manifest() throws Exception {
    String expectedXml = IOUtils//from   ww  w  . j av a2s.c  om
            .toString(this.getClass().getResourceAsStream("/asic/expected-asic-manifest.xml"));

    Behandlingsansvarlig behandlingsansvarlig = Behandlingsansvarlig.builder("123456789")
            .fakturaReferanse("K1").avsenderIdentifikator("0123456789").build();

    Mottaker mottaker = Mottaker.builder("11077941012", "123456", mottakerSertifikat(), "984661185").build();

    Forsendelse forsendelse = Forsendelse.digital(behandlingsansvarlig,
            DigitalPost.builder(mottaker, "Ikke sensitiv tittel").build(),
            Dokumentpakke
                    .builder(Dokument
                            .builder("Vedtak", "vedtak_2398324.pdf",
                                    new ByteArrayInputStream("vedtak".getBytes()))
                            .mimeType("application/pdf").build())
                    .vedlegg(
                            Dokument.builder("informasjon", "info.html",
                                    new ByteArrayInputStream("info".getBytes())).mimeType("text/html").build(),
                            Dokument.builder("journal", "journal.txt",
                                    new ByteArrayInputStream("journal".getBytes())).mimeType("text/plain")
                                    .build())
                    .build())
            .build();

    SDPManifest manifest = sut.createManifest(forsendelse);

    ByteArrayOutputStream xmlBytes = new ByteArrayOutputStream();
    marshaller.marshal(manifest, new StreamResult(xmlBytes));

    assertThat(xmlBytes.toString()).isEqualTo(expectedXml);
}

From source file:de.magicclock.helper.RequestTask.java

@Override
protected String doInBackground(String... uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;/*from  w w  w.  java  2 s.  c om*/
    String responseString = null;
    try {
        response = httpclient.execute(new HttpGet(uri[0]));
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
        } else {
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        responseString = "ERROR ClientProtocolException\n" + e.getStackTrace();
    } catch (IOException e) {
        responseString = "ERROR IOException\n" + e.getStackTrace();
    }
    return responseString;
}

From source file:org.protocoder.network.RequestTask.java

@Override
protected String doInBackground(String... uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;/*from ww w. j  a  va  2s.c o m*/
    String responseString = null;
    try {
        response = httpclient.execute(new HttpGet(uri[0]));
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
        } else {
            // Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        // TODO Handle problems..
    } catch (IOException e) {
        // TODO Handle problems..
    }
    return responseString;
}

From source file:com.cedarsoft.serialization.jackson.test.WithoutTypeTest.java

License:asdf

@Test
public void testNonObjectType() throws Exception {
    EmailSerializer serializer = new EmailSerializer();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    serializer.serialize(new Email("asdf@test.de"), out);

    JsonUtils.assertJsonEquals("\"asdf@test.de\"", out.toString());

    Email mail = serializer.deserialize(new ByteArrayInputStream("\"asdf@test.de\"".getBytes()),
            serializer.getFormatVersion());
    assertThat(mail.getMail()).isEqualTo("asdf@test.de");
}

From source file:org.ldp4j.apps.ldp4ro.servlets.Form2RDFServlet.java

/**
 * Upon receiving data from the RO creation form,
 * 1. parses the request to extract the form data
 * 2. converts them to RDF to generate a RO
 * 3. submit that RO to an LDP server that manages the RO
 *//*from   w  ww . j ava2  s  .  co m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String requestURL = request.getRequestURL().toString();
    logger.debug("Received a POST request on '{}'", requestURL);

    Map<String, String[]> parameterMap = request.getParameterMap();

    RoRDFModel ro = new RoRDFModel(parameterMap);

    Model model = ro.process();

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    model.write(os, "TURTLE");
    String roString = os.toString();

    logger.debug("Form data is converted to RDF ... \n{}", roString);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/ldp4j/ldp-bc/");
    //HttpPost post = new HttpPost("http://linkeddata4.dia.fi.upm.es:8088/ldp4j/ldp-bc/");

    StringEntity body = new StringEntity(roString);
    body.setContentType("text/turtle");
    post.setEntity(body);

    HttpResponse ldpResponse = httpclient.execute(post);

    try {
        int statusCode = ldpResponse.getStatusLine().getStatusCode();
        logger.debug("LDP server responded with {} {}", statusCode,
                ldpResponse.getStatusLine().getReasonPhrase());

        if (statusCode == 201 && ldpResponse.getFirstHeader("Location") != null) {
            String location = ldpResponse.getFirstHeader("Location").getValue();
            logger.debug("URI of the newly created LDPR - {}", location);

            request.setAttribute("newURI", location);

            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/roCreated.jsp");
            dispatcher.forward(request, response);

        } else {
            logger.error("An error occurred while creating the RO. {} {}", statusCode,
                    ldpResponse.getStatusLine().getReasonPhrase());
        }

    } finally {
        post.releaseConnection();
    }

}

From source file:com.contextawareframework.querymodule.RequestQuery.java

@Override
protected String doInBackground(String... uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;//from   w w w  .  j  ava 2s  .c  o m
    String responseString = null;
    try {
        response = httpclient.execute(new HttpGet(uri[0]));
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
        } else {
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        //TODO Handle problems..
    } catch (IOException e) {
        //TODO Handle problems..
    }
    return responseString;
}

From source file:com.cooksys.httpserver.IncomingHttpHandler.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    //put the entity stream into a string - sending this object to JavaFX runlater
    //queue causes the stream to close, so we will have to do it here
    final String messageBody;
    if (request instanceof BasicHttpEntityEnclosingRequest) {
        HttpEntity entity = ((BasicHttpEntityEnclosingRequest) request).getEntity();
        if (entity.getContentLength() < Integer.MAX_VALUE / 2) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            entity.writeTo(stream);//w  w w .j  av  a 2  s .  co m
            messageBody = stream.toString();
        } else {
            messageBody = "Data too large";
        }
    } else {
        messageBody = "";
    }

    //Print the raw request message to the message console
    rawMessage = "\n\n";
    rawMessage += request.getRequestLine().toString() + "\n";

    Header[] headers = request.getAllHeaders();
    for (Header header : headers) {
        rawMessage += header.getName() + ": " + header.getValue() + "\n";
    }
    rawMessage += "\n";
    rawMessage += messageBody;

    //get the default response from the model, and copy it to the already provided HttpResponse parameter
    HttpResponse defaultResponse = serverModel.getResponseList().get(serverModel.getDefaultResponseIndex())
            .encodeResponse();

    response.setStatusLine(defaultResponse.getStatusLine());
    response.setEntity(defaultResponse.getEntity());
    response.setHeaders(defaultResponse.getAllHeaders());

    System.out.println("sending response -> " + response.toString());
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            //update the model with the console message
            String originalConsole = serverModel.getMessageConsole().getValue();
            serverModel.getMessageConsole()
                    .set(originalConsole == null ? rawMessage : originalConsole + rawMessage);
        }
    });

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            //update the model with the new message
            serverModel.incomingRequest(request, messageBody);
        }
    });
    System.out.println("handle() end");
}

From source file:com.urucas.raddio.services.RequestTask.java

@Override
protected String doInBackground(String... uri) {

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;//ww w .j ava2 s. c  o m
    String responseString = null;
    try {
        response = httpclient.execute(new HttpGet(uri[0]));
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();

            if (isCancelled()) {
                rsh.onError("Task cancel");
            }

        } else {
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        rsh.onError(e.getMessage());
    } catch (IOException e) {
        rsh.onError(e.getMessage());
    }
    return responseString;
}