Example usage for java.io OutputStream toString

List of usage examples for java.io OutputStream toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.apache.solr.update.AddBlockUpdateTest.java

@SuppressWarnings("serial")
@Test/*  w  w w .  j a  v  a2  s  .c  o  m*/
public void testSolrJXML() throws IOException {
    UpdateRequest req = new UpdateRequest();

    List<SolrInputDocument> docs = new ArrayList<>();

    SolrInputDocument document1 = new SolrInputDocument() {
        {
            final String id = id();
            addField("id", id);
            addField("parent_s", "X");

            ArrayList<SolrInputDocument> ch1 = new ArrayList<>(Arrays.asList(new SolrInputDocument() {
                {
                    addField("id", id());
                    addField("child_s", "y");
                }
            }, new SolrInputDocument() {
                {
                    addField("id", id());
                    addField("child_s", "z");
                }
            }));

            Collections.shuffle(ch1, random());
            addChildDocuments(ch1);
        }
    };

    SolrInputDocument document2 = new SolrInputDocument() {
        {
            final String id = id();
            addField("id", id);
            addField("parent_s", "A");
            addChildDocument(new SolrInputDocument() {
                {
                    addField("id", id());
                    addField("child_s", "b");
                }
            });
            addChildDocument(new SolrInputDocument() {
                {
                    addField("id", id());
                    addField("child_s", "c");
                }
            });
        }
    };

    docs.add(document1);
    docs.add(document2);

    Collections.shuffle(docs, random());
    req.add(docs);

    RequestWriter requestWriter = new RequestWriter();
    OutputStream os = new ByteArrayOutputStream();
    requestWriter.write(req, os);
    assertBlockU(os.toString());
    assertU(commit());

    final SolrIndexSearcher searcher = getSearcher();
    assertSingleParentOf(searcher, one("yz"), "X");
    assertSingleParentOf(searcher, one("bc"), "A");
}

From source file:org.exoplatform.webservice.cs.calendar.CalendarWebservice.java

/**
 * // w  w  w  .  jav a  2  s. c o  m
 * @param username : requested user name
 * @param eventFeedName : contains eventId and CalType
 * @return : Rss feeds
 * @throws Exception
 */
@SuppressWarnings("unchecked")
@GET
@RolesAllowed("users")
@Path("/event/{username}/{eventFeedName}/")
public Response event(@PathParam("username") String username, @PathParam("eventFeedName") String eventFeedName)
        throws Exception {
    CacheControl cacheControl = new CacheControl();
    cacheControl.setNoCache(true);
    cacheControl.setNoStore(true);
    try {
        if (!isAuthorized(username))
            return Response.status(HTTPStatus.LOCKED).entity("Unauthorized: Access is denied")
                    .cacheControl(cacheControl).build();

        CalendarService calService = (CalendarService) ExoContainerContext.getCurrentContainer()
                .getComponentInstanceOfType(CalendarService.class);
        CalendarImportExport icalEx = calService.getCalendarImportExports(CalendarService.ICALENDAR);
        String eventId = eventFeedName.split(Utils.SPLITTER)[0];
        String type = eventFeedName.split(Utils.SPLITTER)[1].replace(Utils.ICS_EXT, "");
        CalendarEvent event = null;
        if (type.equals(Utils.PRIVATE_TYPE + "")) {
            event = calService.getEvent(username, eventId);
        } else if (type.equals(Utils.SHARED_TYPE + "")) {
            EventQuery eventQuery = new EventQuery();
            eventQuery.setText(eventId);
            event = calService.getEvents(username, eventQuery, null).get(0);
        } else {
            EventQuery eventQuery = new EventQuery();
            eventQuery.setText(eventId);
            event = calService.getPublicEvents(eventQuery).get(0);
        }
        if (event == null) {
            return Response.status(HTTPStatus.NOT_FOUND).entity("Event " + eventId + "is removed")
                    .cacheControl(cacheControl).build();
        }
        OutputStream out = icalEx.exportEventCalendar(event);
        InputStream in = new ByteArrayInputStream(out.toString().getBytes());
        return Response.ok(in, "text/calendar").header("Cache-Control", "private max-age=600, s-maxage=120")
                .header("Content-Disposition", "attachment;filename=\"" + eventId + Utils.ICS_EXT)
                .cacheControl(cacheControl).build();
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug(e.getMessage());
        return Response.status(HTTPStatus.INTERNAL_ERROR).entity(e).cacheControl(cacheControl).build();
    }
}

From source file:org.saiku.adhoc.rest.StandaloneCdaResource.java

@GET
@Produces({ "application/json" })
@Path("/doQuery")
public String doQuery(@QueryParam("solution") String solution, @QueryParam("path") String path,
        @QueryParam("file") String file, @QueryParam("dataAccessId") String dataAccessId,
        @QueryParam("outputType") String outputType) {

    final IParameterProvider pathParams = null;
    final OutputStream out = new ByteArrayOutputStream();

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("outputType", outputType);
    params.put("path", path + "/" + file);
    params.put("solution", "");
    params.put("dataAccessId", dataAccessId);
    IParameterProvider requestParams = new SimpleParameterProvider(params);
    try {/* w w w.ja  v a2  s  .c o m*/
        ccg.doQuery(requestParams, out);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return out.toString();

}

From source file:com.comcast.cmb.test.tools.CNSTestingUtils.java

public static String doGetTopicAttributes(CNSControllerServlet cns, User user, OutputStream out,
        String topicArn) throws Exception {
    SimpleHttpServletRequest request = new SimpleHttpServletRequest();
    Map<String, String[]> params = new HashMap<String, String[]>();

    addParam(params, "Action", "GetTopicAttributes");
    if (topicArn != null) {
        addParam(params, "TopicArn", topicArn);
    }/*from   w  ww . j ava  2 s  .c  o m*/

    addParam(params, "AWSAccessKeyId", user.getAccessKey());

    request.setParameterMap(params);
    ((SimpleHttpServletRequest) request).setParameterMap(params);
    SimpleHttpServletResponse response = new SimpleHttpServletResponse();
    response.setOutputStream(out);

    cns.doGet(request, response);
    response.getWriter().flush();

    return out.toString();
}

From source file:uk.org.lidalia.sysoutslf4j.integration.TestSysOutOverSlf4J.java

@Test
public void juliConsoleAppenderStillLogsToConsole() throws Exception {
    OutputStream newSysErr = setUpMockSystemOutput(SystemOutput.ERR);
    SysOutOverSLF4J.sendSystemOutAndErrToSLF4J();

    java.util.logging.Logger log = java.util.logging.Logger.getLogger("");
    for (Handler handler : log.getHandlers()) {
        log.removeHandler(handler);/*from w ww. j a va  2  s.c  om*/
    }
    log.addHandler(new ConsoleHandler());
    log.info("Should reach the old syserr");

    assertThat(newSysErr.toString(), containsString("INFO: Should reach the old syserr"));
}

From source file:com.jivesoftware.jive.deployer.jaxrs.util.ResponseHelperTest.java

@Test
public void testErrorResponse() throws Exception {
    ObjectNode jsonNode = objectMapper.createObjectNode();
    jsonNode.put("Foobar", true);
    String message = "This is a BAD request!";
    Exception e = new Exception();
    OutputStream outputStream = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(outputStream);
    e.printStackTrace(printStream);//  w  w w. j  a va 2  s. c  o m
    Response response = ResponseHelper.INSTANCE.errorResponse(Response.Status.BAD_REQUEST, message, e,
            jsonNode);
    assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
    String bodyString = objectMapper.writeValueAsString(response.getEntity());
    System.out.println(bodyString);
    ObjectNode body = (ObjectNode) objectMapper.readTree(bodyString);
    assertEquals(body.get("message").textValue(), message);
    assertEquals(body.get("trace").textValue(), outputStream.toString());
    assertEquals(body.get("relatedData"), jsonNode);
}

From source file:com.github.cshubhamrao.MediaConverter.MainUI.java

/** Runs ffmpeg -version */
@Override/*from  w  ww  . jav a  2  s . com*/
protected Void doInBackground() {
    ffmpeg = FFMpegLoader.getFFMpegExecutable();
    if (ffmpeg != null) {
        try {
            cmd = new CommandLine(ffmpeg);
            cmd.addArgument("-version");
            OutputStream outputStream = new ByteArrayOutputStream();
            DefaultExecutor exec = new DefaultExecutor();
            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
            exec.setStreamHandler(streamHandler);
            ExecuteWatchdog watchdog = new ExecuteWatchdog(10000);
            exec.setWatchdog(watchdog);
            exec.execute(cmd);
            publish(outputStream.toString());
        } catch (ExecuteException ex) {
            Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return null;
}

From source file:org.exoplatform.webservice.cs.calendar.CalendarWebservice.java

/**
 * /* w  w w. j  ava  2 s .c om*/
 * @param username : 
 * @param calendarId
 * @param type
 * @param eventId
 * @return Icalendar data
 * @throws Exception
 */
@GET
@RolesAllowed("users")
@Path("/private/{username}/{calendarId}/{type}")
public Response privateProcess(@PathParam("username") String username,
        @PathParam("calendarId") String calendarId, @PathParam("type") String type) throws Exception {
    CacheControl cacheControl = new CacheControl();
    cacheControl.setNoCache(true);
    cacheControl.setNoStore(true);
    try {
        if (!isAuthorized(username))
            return Response.status(HTTPStatus.LOCKED).entity("Unauthorized: Access is denied")
                    .cacheControl(cacheControl).build();
        CalendarService calService = (CalendarService) ExoContainerContext.getCurrentContainer()
                .getComponentInstanceOfType(CalendarService.class);
        CalendarImportExport icalEx = calService.getCalendarImportExports(CalendarService.ICALENDAR);
        OutputStream out = icalEx.exportCalendar(username, Arrays.asList(calendarId), type, -1);
        InputStream in = new ByteArrayInputStream(out.toString().getBytes());
        return Response.ok(in, "text/calendar").header("Cache-Control", "private max-age=600, s-maxage=120")
                .header("Content-Disposition", "attachment;filename=\"" + calendarId + ".ics")
                .cacheControl(cacheControl).build();
    } catch (NullPointerException ne) {
        return Response.ok(null, "text/calendar").header("Cache-Control", "private max-age=600, s-maxage=120")
                .header("Content-Disposition", "attachment;filename=\"" + calendarId + ".ics")
                .cacheControl(cacheControl).build();
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug(e.getMessage());
        return Response.status(HTTPStatus.INTERNAL_ERROR).entity(e).cacheControl(cacheControl).build();
    }
}

From source file:ratpack.codahale.metrics.internal.WebSocketReporter.java

@Override
@SuppressWarnings("rawtypes")
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
        SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters,
        SortedMap<String, Timer> timers) {
    try {/* w  w  w .j av a 2  s .  co m*/
        OutputStream out = new ByteArrayOutputStream();
        JsonGenerator json = factory.createGenerator(out);

        json.writeStartObject();
        json.writeNumberField("timestamp", clock.getTime());
        writeTimers(json, timers);
        writeGauges(json, gauges);
        writeMeters(json, meters);
        writeCounters(json, counters);
        writeHistograms(json, histograms);
        json.writeEndObject();

        json.flush();
        json.close();

        metricsBroadcaster.broadcast(out.toString());
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Exception encountered while reporting metrics: " + e.getLocalizedMessage());
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.processors.FilePackagerFastTest.java

private void checkTar(final File f_tar, final Boolean isMafArchive) throws IOException {

    FileReader origReader = null;
    TarArchiveInputStream tarIn = null;/*from w  w w. j  ava  2s . c  o  m*/

    try {
        //we're going to open each of the included files in turn and compare to our tiny
        //original input file.  So first, need to read the original file into a string.
        StringBuilder origBuf = new StringBuilder();
        char[] cbuf = new char[1024];
        //noinspection IOResourceOpenedButNotSafelyClosed
        origReader = new FileReader(THIS_FOLDER + TEST_DOWNLOADFILE);
        int iread;
        while ((iread = origReader.read(cbuf)) != -1) {
            for (int i = 0; i < iread; i++) {
                origBuf.append(cbuf[i]);
            }
        }
        String origText = origBuf.toString();
        //noinspection IOResourceOpenedButNotSafelyClosed
        tarIn = new TarArchiveInputStream(new FileInputStream(f_tar));
        TarArchiveEntry entry;
        int i = 0;
        entry = tarIn.getNextTarEntry();
        assertEquals("file_manifest.txt", entry.getName());
        if (isMafArchive) {
            entry = tarIn.getNextTarEntry();
            assertEquals("README_DCC.txt", entry.getName());
        }
        while ((entry = tarIn.getNextTarEntry()) != null) {
            //compare to input file
            File expectedName = new File("platform" + i + "/center" + i + "/Level_1/f" + i + ".idat");
            assertEquals(expectedName, new File(entry.getName()));
            byte[] content = new byte[2056];
            OutputStream byteOut = new ByteArrayOutputStream(2056);
            //noinspection ResultOfMethodCallIgnored
            tarIn.read(content);
            byteOut.write(content);
            byteOut.close();
            assertEquals(origText, byteOut.toString().trim());
            i++;
        }
        assertEquals(i, HOWMANYFILES);
    } finally {
        IOUtils.closeQuietly(origReader);
        IOUtils.closeQuietly(tarIn);
    }
}