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.nuxeo.ecm.rating.operations.MostLiked.java

protected JSONObject buildFromDocument(Activity activity) throws IOException {
    DocumentModel doc = session.getDocument(new IdRef(getDocumentId(activity.getTarget())));
    Integer rating = Integer.valueOf(activity.getObject());
    Integer hasRated = Integer.valueOf(activity.getContext());

    OutputStream out = new ByteArrayOutputStream();
    JsonGenerator jg = JsonHelper.createJsonGenerator(out);

    writeDocument(doc, jg);/*from  w  w  w  .  j av a 2  s.  co m*/

    Map<String, Object> value = new HashMap<String, Object>();
    value.put("rating", rating);
    value.put("document", JSONObject.fromObject(out.toString()));
    value.put("url", getDocumentUrl(doc));
    value.put("hasUserLiked", hasRated);
    value.put("type", "document");

    return JSONObject.fromObject(value);
}

From source file:org.testeditor.dsl.common.util.MavenExecutor.java

private String[] linesFromMavenVersionCall() throws IOException {
    OutputStream versionOut = new ByteArrayOutputStream();
    int infoResult = executeInNewJvm("-version", ".", "", new NullProgressMonitor(), versionOut);
    if (infoResult != IStatus.OK) {
        logger.error("Error during determine of maven version");
        return null;
    }/*from w w  w. j  av a  2s .c  o m*/
    return versionOut.toString().split("(\r)?\n");
}

From source file:com.redhat.rhn.taskomatic.task.repomd.OtherXmlWriter.java

/**
 *
 * @param pkgDto pkg info to add to xml/*from  ww  w  .j a v  a2  s.c  o m*/
 */
public void addPackage(PackageDto pkgDto) {

    try {
        String xml = pkgDto.getOtherXml();
        if (ConfigDefaults.get().useDBRepodata() && !StringUtils.isEmpty(xml)) {
            if (xml != null) {
                handler.addCharacters(xml);
                return;
            }
        }

        OutputStream st = new ByteArrayOutputStream();
        SimpleContentHandler tmpHandler = getTemporaryHandler(st);
        tmpHandler.startDocument();

        addPackageBoilerplate(tmpHandler, pkgDto);
        addPackageChangelog(pkgDto, tmpHandler);
        tmpHandler.endElement("package");
        tmpHandler.endDocument();

        String pkg = st.toString();
        PackageManager.updateRepoOther(pkgDto.getId(), pkg);
        handler.addCharacters(pkg);

    } catch (SAXException e) {
        throw new RepomdRuntimeException(e);
    } catch (SQLException e) {
        SqlExceptionTranslator.sqlException(e);
    }
}

From source file:com.synopsys.arc.jenkinsci.plugins.cygwinprocesskiller.util.CygwinKillHelper.java

/**
 * Checks that Cygwin is available on the host.
 *///  ww  w  . j  a v a  2s  .  c  om
public boolean isCygwin() throws InterruptedException {
    OutputStream str = new ByteArrayOutputStream();
    try { // Catch tool installation exceptions
        execCommand("uname", str, str, "-a");
    } catch (IOException ex) {
        logError(Messages.Message_CygwinCheckFailed() + ex.getMessage());
        return false;
    }
    return str.toString().startsWith(CYGWIN_START_PREFIX);
}

From source file:com.taobao.adfs.util.Utilities.java

public static String getThrowableStackTrace(Throwable t) {
    PrintStream printStream = null;
    try {/*from   w w  w.ja v a2  s .c  om*/
        OutputStream outputStream = null;
        outputStream = new ByteArrayOutputStream(1024);
        printStream = new PrintStream(outputStream);
        t.printStackTrace(printStream);
        printStream.flush();
        return outputStream.toString();
    } catch (Exception e) {
        return "unknow";
    } finally {
        if (printStream != null)
            printStream.close();
    }
}

From source file:com.csc.fi.ioapi.utils.JerseyJsonLDClient.java

public static Response getExportGraph(String graph, boolean raw, String lang, String ctype) {

    try {//w w  w. j  ava2  s.c om

        ContentType contentType = ContentType.create(ctype);

        Lang rdfLang = RDFLanguages.contentTypeToLang(contentType);

        if (rdfLang == null) {
            logger.info("Unknown RDF type: " + ctype);
            return JerseyResponseManager.notFound();
        }

        DatasetAccessor accessor = DatasetAccessorFactory.createHTTP(services.getCoreReadAddress());
        Model model = accessor.getModel(graph);

        OutputStream out = new ByteArrayOutputStream();

        Response response = JerseyJsonLDClient.getGraphResponseFromService(graph + "#ExportGraph",
                services.getCoreReadAddress(), ctype);

        if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
            return JerseyResponseManager.unexpected();
        }

        /* TODO: Remove builders */
        ResponseBuilder rb;
        RDFDataMgr.write(out, model, rdfLang);

        if (rdfLang.equals(Lang.JSONLD)) {

            Map<String, Object> jsonModel = null;
            try {
                jsonModel = (Map<String, Object>) JsonUtils.fromString(out.toString());
            } catch (IOException ex) {
                Logger.getLogger(ExportModel.class.getName()).log(Level.SEVERE, null, ex);
                return JerseyResponseManager.unexpected();
            }

            Map<String, Object> frame = new HashMap<String, Object>();
            //Map<String,Object> frame = (HashMap<String,Object>) LDHelper.getExportContext();

            Map<String, Object> context = (Map<String, Object>) jsonModel.get("@context");

            context.putAll(LDHelper.CONTEXT_MAP);

            frame.put("@context", context);
            frame.put("@type", "owl:Ontology");

            Object data;

            try {
                data = JsonUtils.fromInputStream(response.readEntity(InputStream.class));

                rb = Response.status(response.getStatus());

                try {
                    JsonLdOptions options = new JsonLdOptions();
                    Object framed = JsonLdProcessor.frame(data, frame, options);

                    ObjectMapper mapper = new ObjectMapper();

                    rb.entity(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(framed));

                } catch (NullPointerException ex) {
                    logger.log(Level.WARNING, null, "DEFAULT GRAPH IS NULL!");
                    return rb.entity(JsonUtils.toString(data)).build();
                } catch (JsonLdError ex) {
                    logger.log(Level.SEVERE, null, ex);
                    return JerseyResponseManager.serverError();
                }

            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
                return JerseyResponseManager.serverError();
            }

        } else {
            rb = Response.status(response.getStatus());
            rb.entity(response.readEntity(InputStream.class));
        }

        if (!raw) {
            rb.type(contentType.getContentType());
        } else {
            rb.type("text/plain");
        }

        return rb.build();

    } catch (Exception ex) {
        logger.log(Level.WARNING, "Expect the unexpected!", ex);
        return JerseyResponseManager.serverError();
    }

}

From source file:net.sf.jasperreports.olap.xmla.Olap4jXmlaQueryExecuter.java

/**
 * Parses the result into this class's structure
 * //from   w ww  .j  ava 2 s. c  o  m
 * @param result
 *            The CellSet query result
 */
protected void parseResult(CellSet result) throws JRException {
    if (log.isDebugEnabled()) {
        OutputStream bos = new ByteArrayOutputStream();
        CellSetFormatter formatter = new RectangularCellSetFormatter(true);
        formatter.format(result, new PrintWriter(bos, true));
        log.debug("Result:\n" + bos.toString());
    }

    xmlaResult = new JRXmlaResult();

    parseAxes(result);

    parseCellDataElement(result);
}

From source file:org.openmrs.module.ModuleUtil.java

/**
 * Downloads the contents of a URL and copies them to a string (Borrowed from oreilly)
 *
 * @param url//from  w  w w  .j av  a  2  s  .co  m
 * @return String contents of the URL
 * @should return an update rdf page for old https dev urls
 * @should return an update rdf page for old https module urls
 * @should return an update rdf page for module urls
 */
public static String getURL(URL url) {
    InputStream in = null;
    OutputStream out = null;
    String output = "";
    try {
        in = getURLStream(url);
        if (in == null) {
            // skip this module if updateURL is not defined
            return "";
        }

        out = new ByteArrayOutputStream();
        OpenmrsUtil.copyFile(in, out);
        output = out.toString();
    } catch (IOException io) {
        log.warn("io while reading: " + url, io);
    } finally {
        try {
            in.close();
        } catch (Exception e) {
            /* pass */}
        try {
            out.close();
        } catch (Exception e) {
            /* pass */}
    }

    return output;
}

From source file:org.opencastproject.workflow.handler.mediapackagepost.MediaPackagePostOperationHandler.java

/**
 * {@inheritDoc}//from   ww w  . j  ava2  s .  co m
 * 
 * @see org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance,
 *      JobContext)
 */
public WorkflowOperationResult start(final WorkflowInstance workflowInstance, JobContext context)
        throws WorkflowOperationException {

    // get configuration
    WorkflowOperationInstance currentOperation = workflowInstance.getCurrentOperation();
    Configuration config = new Configuration(currentOperation);

    MediaPackage mp = workflowInstance.getMediaPackage();

    /* Check if we need to replace the Mediapackage we got with the published
     * Mediapackage from the Search Service */
    if (config.mpFromSearch) {
        SearchQuery searchQuery = new SearchQuery();
        searchQuery.withId(mp.getIdentifier().toString());
        SearchResult result = searchService.getByQuery(searchQuery);
        if (result.size() != 1) {
            throw new WorkflowOperationException("Received multiple results for identifier" + "\""
                    + mp.getIdentifier().toString() + "\" from search service. ");
        }
        logger.info("Getting Mediapackage from Search Service");
        mp = result.getItems()[0].getMediaPackage();
    }

    try {

        logger.info("Submitting \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") as "
                + config.getFormat().name() + " to " + config.getUrl().toString());

        // serialize MediaPackage to target format
        OutputStream serOut = new ByteArrayOutputStream();
        MediaPackageParser.getAsXml(mp, serOut, false);
        String mpStr = serOut.toString();
        serOut.close();
        if (config.getFormat() == Configuration.Format.JSON) {
            JSONObject json = XML.toJSONObject(mpStr);
            mpStr = json.toString();
            if (mpStr.startsWith("{\"ns2:")) {
                mpStr = (new StringBuilder()).append("{\"").append(mpStr.substring(6)).toString();
            }
        }

        // Log mediapackge
        if (config.debug()) {
            logger.info(mpStr);
        }

        // constrcut message body
        List<NameValuePair> data = new ArrayList<NameValuePair>();
        data.add(new BasicNameValuePair("mediapackage", mpStr));
        data.addAll(config.getAdditionalFields());

        // construct POST
        HttpPost post = new HttpPost(config.getUrl());
        post.setEntity(new UrlEncodedFormEntity(data, config.getEncoding()));

        // execute POST
        DefaultHttpClient client = new DefaultHttpClient();

        // Handle authentication
        if (config.authenticate()) {
            URL targetUrl = config.getUrl().toURL();
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(targetUrl.getHost(), targetUrl.getPort()), config.getCredentials());
        }

        HttpResponse response = client.execute(post);

        // throw Exception if target host did not return 200
        int status = response.getStatusLine().getStatusCode();
        if (status == 200) {
            if (config.debug()) {
                logger.info("Successfully submitted \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString()
                        + ") to " + config.getUrl().toString() + ": 200 OK");
            }
        } else if (status == 418) {
            logger.warn("Submitted \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") to "
                    + config.getUrl().toString() + ": The target claims to be a teapot. "
                    + "The Reason for this is probably an insane programmer.");
        } else {
            throw new WorkflowOperationException(
                    "Faild to submit \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + "), "
                            + config.getUrl().toString() + " answered with: " + Integer.toString(status));
        }
    } catch (Exception e) {
        if (e instanceof WorkflowOperationException) {
            throw (WorkflowOperationException) e;
        } else {
            throw new WorkflowOperationException(e);
        }
    }
    return createResult(mp, Action.CONTINUE);
}

From source file:sapience.features.streams.kml.TestEasy.java

public void writeEasy() throws IOException {
    OutputStream os = new OutputStream() {
        StringBuffer sb = new StringBuffer();

        @Override/*  w ww . j a  v a2  s. c om*/
        public void write(int b) throws IOException {
            sb.append((char) b);
        }

        public String toString() {
            return sb.toString();
        }
    };

    streams.write(res, os);

    String expected = IOUtils.toString(this.getClass().getResourceAsStream(out));
    String actual = os.toString();

    System.out.println(expected.trim());
    System.out.println(actual.trim());

}