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.kuali.mobility.tours.controllers.ToursController.java

@RequestMapping(value = "kml/{tourId}", method = RequestMethod.GET)
public String downloadKml(@PathVariable("tourId") Long tourId, HttpServletResponse response) {
    Tour tour = toursService.findTourById(tourId);
    Kml kml = toursService.createTourKml(tour);
    OutputStream os = new ByteArrayOutputStream();
    try {//from  w w w . j av  a  2s  .  c  om
        kml.marshal(os);
    } catch (Exception e) {
    }
    byte[] data = os.toString().getBytes();
    response.setContentType("application/vnd.google-earth.kml+xml");
    response.setContentLength(data.length);
    response.setHeader("Content-Disposition", "attachment; filename=\"" + tour.getName() + ".kml\"");
    try {
        response.getOutputStream().write(data, 0, data.length);
    } catch (IOException e) {
    }
    return null;
}

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

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

    addParam(params, "Action", "SetSubscriptionAttributes");
    if (subscriptionArn != null) {
        addParam(params, "SubscriptionArn", subscriptionArn);
    }//w  w  w.  jav a  2  s .  c  om
    if (attributeName != null) {
        addParam(params, "AttributeName", attributeName);
    }

    if (attributeValue != null) {
        addParam(params, "AttributeValue", attributeValue);
    }

    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:org.kuali.mobility.maps.service.LocationServiceImpl.java

private String documentToString(Document doc) {
    String xml = "";
    try {//w ww.j a va 2  s  .co m
        OutputFormat format = new OutputFormat(doc);
        format.setIndenting(true);
        format.setLineWidth(80);
        OutputStream out = new ByteArrayOutputStream();
        XMLSerializer serializer = new XMLSerializer(format);
        serializer.setOutputByteStream(out);
        serializer.serialize(doc);
        xml = out.toString();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
    return xml;
}

From source file:info.rmapproject.api.responsemgr.AgentResponseManager.java

/**
 * Retrieves RMap Agent in requested RDF format and forms an HTTP response.
 *
 * @param strAgentUri the Agent URI// w w w. j av  a 2  s.c o m
 * @param returnType the return media type
 * @return HTTP Response
 * @throws RMapApiException the RMap API Exception
 */
public Response getRMapAgent(String strAgentUri, RdfMediaType returnType) throws RMapApiException {
    boolean reqSuccessful = false;
    Response response = null;
    try {
        if (strAgentUri == null || strAgentUri.length() == 0) {
            throw new RMapApiException(ErrorCode.ER_NO_OBJECT_URI_PROVIDED);
        }
        if (returnType == null) {
            returnType = Constants.DEFAULT_RDF_TYPE;
        }

        URI uriAgentId = convertPathStringToURI(strAgentUri);

        RMapAgent rmapAgent = rmapService.readAgent(uriAgentId);
        if (rmapAgent == null) {
            throw new RMapApiException(ErrorCode.ER_CORE_READ_AGENT_RETURNED_NULL);
        }

        OutputStream agentOutput = rdfHandler.agent2Rdf(rmapAgent, returnType.getRdfType());
        if (agentOutput == null) {
            throw new RMapApiException(ErrorCode.ER_CORE_RDFHANDLER_OUTPUT_ISNULL);
        }

        RMapStatus status = rmapService.getAgentStatus(uriAgentId);
        if (status == null) {
            throw new RMapApiException(ErrorCode.ER_CORE_GET_STATUS_RETURNED_NULL);
        }
        String linkRel = "<" + status.getPath().toString() + ">" + ";rel=\"" + Terms.RMAP_HASSTATUS_PATH + "\"";

        response = Response.status(Response.Status.OK).entity(agentOutput.toString())
                .location(new URI(Utils.makeAgentUrl(strAgentUri))).header("Link", linkRel) //switch this to link()
                .type(HttpTypeMediator.getResponseRMapMediaType("agent", returnType.getRdfType())) //TODO move version number to a property?
                .build();

        reqSuccessful = true;

    } catch (RMapApiException ex) {
        throw RMapApiException.wrap(ex);
    } catch (RMapDefectiveArgumentException ex) {
        throw RMapApiException.wrap(ex, ErrorCode.ER_GET_AGENT_BAD_ARGUMENT);
    } catch (RMapAgentNotFoundException ex) {
        throw RMapApiException.wrap(ex, ErrorCode.ER_AGENT_OBJECT_NOT_FOUND);
    } catch (RMapException ex) {
        if (ex.getCause() instanceof RMapDeletedObjectException) {
            throw RMapApiException.wrap(ex, ErrorCode.ER_OBJECT_DELETED);
        } else if (ex.getCause() instanceof RMapTombstonedObjectException) {
            throw RMapApiException.wrap(ex, ErrorCode.ER_OBJECT_TOMBSTONED);
        } else if (ex.getCause() instanceof RMapObjectNotFoundException) {
            throw RMapApiException.wrap(ex, ErrorCode.ER_OBJECT_NOT_FOUND);
        } else {
            throw RMapApiException.wrap(ex, ErrorCode.ER_CORE_GENERIC_RMAP_EXCEPTION);
        }
    } catch (Exception ex) {
        throw RMapApiException.wrap(ex, ErrorCode.ER_UNKNOWN_SYSTEM_ERROR);
    } finally {
        if (rmapService != null)
            rmapService.closeConnection();
        if (!reqSuccessful && response != null)
            response.close();
    }
    return response;
}

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

public static void confirmSubscription(CNSControllerServlet cns, User user, OutputStream out, String topicArn,
        String token, String authOnSub) throws Exception {

    SimpleHttpServletRequest request = new SimpleHttpServletRequest();
    //System.out.println("Deleting Topic arn is:" + arn);
    Map<String, String[]> params = new HashMap<String, String[]>();
    addParam(params, "Action", "ConfirmSubscription");
    addParam(params, "AWSAccessKeyId", user.getAccessKey());
    if (topicArn != null)
        addParam(params, "TopicArn", topicArn);
    if (token != null)
        addParam(params, "Token", token);
    if (authOnSub != null)
        addParam(params, "AuthenticateOnUnsubscribe", authOnSub);

    request.setParameterMap(params);/*from   w ww.j  a v a 2 s  . c om*/
    SimpleHttpServletResponse response = new SimpleHttpServletResponse();
    response.setOutputStream(out);
    logger.debug("confirmSubscription");
    cns.doGet(request, response);
    //System.out.println("Done Delete Topic Arn:" + arn);

    response.getWriter().flush();
    logger.debug("confirmSubscription Out:" + out.toString());

}

From source file:com.alfaariss.oa.util.configuration.handler.jdbc.JDBCConfigurationHandler.java

/**
 * Saves the database configuration using the update query.
 * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document)
 *//*w  w w.  j  a  v  a  2s.  com*/
public void saveConfiguration(Document oConfigurationDocument) throws ConfigurationException {
    Connection oConnection = null;
    OutputStream os = null;
    PreparedStatement ps = null;

    try {
        os = new ByteArrayOutputStream();

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(oConfigurationDocument), new StreamResult(os));

        //Save to DB
        oConnection = _oDataSource.getConnection();
        ps = oConnection.prepareStatement(_sUpdateQuery);
        ps.setString(1, os.toString());
        ps.setString(2, _sConfigId);
        ps.executeUpdate();
    } catch (SQLException e) {
        _logger.error("Database error while writing configuration, SQL eror", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    } catch (TransformerException e) {
        _logger.error("Error while transforming document", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    } catch (Exception e) {
        _logger.error("Internal error during during configuration save", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    } finally {

        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
            _logger.debug("Error closing configuration outputstream", e);
        }

        try {
            if (ps != null)
                ps.close();
        } catch (SQLException e) {
            _logger.debug("Error closing statement", e);
        }

        try {
            if (oConnection != null)
                oConnection.close();
        } catch (SQLException e) {
            _logger.debug("Error closing connection", e);
        }
    }
}

From source file:org.elasticwarehouse.core.parsers.ElasticWarehouseFileParserAuto.java

public boolean parse() throws IOException {
    boolean ret = false;
    InputStream is = null;//from w  w w  . j  a  v a2s  . com
    file.statParse();
    try {
        LOGGER.info("Parsing " + file.getOrginalFname() + " (" + file.getUploadedFilename() + ")");
        is = new BufferedInputStream(new FileInputStream(new File(file.getUploadedFilename())));

        Parser parser = new AutoDetectParser();
        OutputStream output = new OutputStringStream();
        ContentHandler handler = new BodyContentHandler(output);//System.out);
        //ContentHandler h2 = new EmbeddedContentHandler(handler);
        Metadata metadata = new Metadata();
        //ExtractParser extractParser = new ExtractParser(parser);
        //ParseContext context = new ParseContext();
        //context.set(Parser.class, extractParser);
        //context.set(EmbeddedDocumentExtractor.class, new FileEmbeddedDocumentExtractor());
        ParseContext parseContext = new ParseContext();
        //parseContext.set(Parser.class, new TikaImageExtractingParser());
        parseContext.set(Parser.class, new ElasticWarehouseParserAll(parser, file, conf_));

        parser.parse(is, handler/*handler*/, metadata, parseContext);

        file.fill(metadata, output.toString());
        ret = true;

    } catch (IOException e) {
        EWLogger.logerror(e);
        e.printStackTrace();
    } catch (java.lang.ExceptionInInitializerError e) {
        EWLogger.logerror(e);
        e.printStackTrace();
    } catch (TikaException e) {
        Exception e2 = (Exception) ExceptionUtils.getRootCause(e);
        if (e2 instanceof UnsupportedZipFeatureException) {
            //do nothing, format unsupported
            ret = true;
        } else if (e2 instanceof EncryptedPowerPointFileException) {
            //do nothing, format unsupported
            ret = true;
        } else if (e instanceof org.apache.tika.exception.EncryptedDocumentException) {
            //do nothing, format unsupported
            ret = true;
        } else if (e2 instanceof org.apache.poi.EncryptedDocumentException) {
            //do nothing, format unsupported
            ret = true;
        } else if (e2 instanceof org.apache.tika.exception.EncryptedDocumentException) {
            //do nothing, format unsupported
            ret = true;
        } else {
            EWLogger.logerror(e);
            e.printStackTrace();

            //i.e. for org.apache.tika.exception.TikaException: cannot parse detached pkcs7 signature (no signed data to parse)
            ret = true;
        }
    } catch (SAXException e) {
        EWLogger.logerror(e);
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                EWLogger.logerror(e);
                e.printStackTrace();
            }
        }
    }

    //add metadata supporoit to teh mapping
    file.endParse();
    LOGGER.info("Parsing " + file.getOrginalFname() + " took " + file.getParsingTime() + " ms");
    /*if( file == null )
       return false;
    InputStream is = null;
     try {
       is = new FileInputStream(file.getFilename());
       ContentHandler contenthandler = new BodyContentHandler();
       Metadata metadata = new Metadata();
       PDFParser pdfparser = new PDFParser();
       pdfparser.parse(is, contenthandler, metadata, new ParseContext());
       System.out.println(contenthandler.toString());
     }
     catch (Exception e) {
       e.printStackTrace();
     }
     finally {
         if (is != null) is.close();
     }*/
    return ret;
}

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

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

    addParam(params, "Action", "Publish");
    if (message != null) {
        addParam(params, "Message", message);
    }/*from  ww  w  .  j  a va2  s. com*/
    if (messageStructure != null) {
        addParam(params, "MessageStructure", messageStructure);
    }
    if (subject != null) {
        addParam(params, "Subject", subject);
    }
    if (topicArn != null) {
        addParam(params, "TopicArn", topicArn);
    }
    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:com.mediaworx.xmlutils.XmlHelper.java

/**
 * Converts the document to a formatted XML String (indentation level is 4) using the given encoding.
 * @param document      The document to be converted to String
 * @param cdataElements String array containing the names of all elements that are to be added within CDATA sections
 * @param encoding      encoding to be used (added in the XML declaration)
 * @return  the String representation of the given Document
 *//*from  w  w  w  .  j ava  2 s.c o  m*/
public String getXmlStringFromDocument(Document document, String[] cdataElements, String encoding) {
    cleanEmptyTextNodes(document);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = tf.newTransformer();
    } catch (TransformerConfigurationException e) {
        LOG.error("Exception configuring the XML transformer", e);
        return "";
    }
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    if (cdataElements != null && cdataElements.length > 0) {
        String cdataElementsJoined = StringUtils.join(cdataElements, ' ');
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cdataElementsJoined);
    }
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    OutputStream out = new ByteArrayOutputStream();
    try {
        transformer.transform(new DOMSource(document), new StreamResult(out));
    } catch (TransformerException e) {
        LOG.error("Exception transforming the XML document to String", e);
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            // it seems the output stream was closed already
            LOG.warn("Exception closing the output stream", e);
        }
    }
    StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"").append(encoding)
            .append("\"?>\n");
    xml.append(out.toString());
    return xml.toString();
}

From source file:org.apache.hadoop.hive.metastore.tools.TestSchemaToolForMetastore.java

/**
 * Test schema upgrade//from   w ww .  j ava 2  s  .co m
 */
@Test
public void testSchemaUpgrade() throws Exception {
    boolean foundException = false;
    // Initialize 1.2.0 schema
    execute(new SchemaToolTaskInit(), "-initSchemaTo 1.2.0");
    // verify that driver fails due to older version schema
    try {
        schemaTool.verifySchemaVersion();
    } catch (HiveMetaException e) {
        // Expected to fail due to old schema
        foundException = true;
    }
    if (!foundException) {
        throw new Exception("Hive operations shouldn't pass with older version schema");
    }

    // Generate dummy pre-upgrade script with errors
    String invalidPreUpgradeScript = writeDummyPreUpgradeScript(0, "upgrade-2.3.0-to-3.0.0.derby.sql",
            "foo bar;");
    // Generate dummy pre-upgrade scripts with valid SQL
    String validPreUpgradeScript0 = writeDummyPreUpgradeScript(1, "upgrade-2.3.0-to-3.0.0.derby.sql",
            "CREATE TABLE schema_test0 (id integer);");
    String validPreUpgradeScript1 = writeDummyPreUpgradeScript(2, "upgrade-2.3.0-to-3.0.0.derby.sql",
            "CREATE TABLE schema_test1 (id integer);");

    // Capture system out and err
    schemaTool.setVerbose(true);
    OutputStream stderr = new ByteArrayOutputStream();
    PrintStream errPrintStream = new PrintStream(stderr);
    System.setErr(errPrintStream);
    OutputStream stdout = new ByteArrayOutputStream();
    PrintStream outPrintStream = new PrintStream(stdout);
    System.setOut(outPrintStream);

    // Upgrade schema from 0.7.0 to latest
    execute(new SchemaToolTaskUpgrade(), "-upgradeSchemaFrom 1.2.0");

    // Verify that the schemaTool ran pre-upgrade scripts and ignored errors
    Assert.assertTrue(stderr.toString().contains(invalidPreUpgradeScript));
    Assert.assertTrue(stderr.toString().contains("foo"));
    Assert.assertFalse(stderr.toString().contains(validPreUpgradeScript0));
    Assert.assertFalse(stderr.toString().contains(validPreUpgradeScript1));
    Assert.assertTrue(stdout.toString().contains(validPreUpgradeScript0));
    Assert.assertTrue(stdout.toString().contains(validPreUpgradeScript1));

    // Verify that driver works fine with latest schema
    schemaTool.verifySchemaVersion();
}