Example usage for java.io StringBufferInputStream StringBufferInputStream

List of usage examples for java.io StringBufferInputStream StringBufferInputStream

Introduction

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

Prototype

public StringBufferInputStream(String s) 

Source Link

Document

Creates a string input stream to read data from the specified string.

Usage

From source file:it.eng.spagobi.analiticalmodel.execution.service.PrintNotesAction.java

public void doService() {
    logger.debug("IN");

    ExecutionInstance executionInstance;
    executionInstance = getContext().getExecutionInstance(ExecutionInstance.class.getName());
    String executionIdentifier = new BIObjectNotesManager()
            .getExecutionIdentifier(executionInstance.getBIObject());
    Integer biobjectId = executionInstance.getBIObject().getId();
    List globalObjNoteList = null;
    try {/*from w w w.  ja v a  2 s  . com*/
        globalObjNoteList = DAOFactory.getObjNoteDAO().getListExecutionNotes(biobjectId, executionIdentifier);
    } catch (EMFUserError e1) {
        logger.error("Error in retrieving obj notes", e1);
        return;
    } catch (Exception e1) {
        logger.error("Error in retrieving obj notes", e1);
        return;
    }
    //mantains only the personal notes and others one only if they have PUBLIC status
    List objNoteList = new ArrayList();
    UserProfile profile = (UserProfile) this.getUserProfile();
    String userId = (String) profile.getUserId();
    for (int i = 0, l = globalObjNoteList.size(); i < l; i++) {
        ObjNote objNote = (ObjNote) globalObjNoteList.get(i);
        if (objNote.getIsPublic()) {
            objNoteList.add(objNote);
        } else if (objNote.getOwner().equalsIgnoreCase(userId)) {
            objNoteList.add(objNote);
        }
    }

    String outputType = "PDF";
    RequestContainer requestContainer = getRequestContainer();
    SourceBean sb = requestContainer.getServiceRequest();
    outputType = (String) sb.getAttribute(SBI_OUTPUT_TYPE);
    if (outputType == null)
        outputType = "PDF";

    String templateStr = getTemplateTemplate();

    //JREmptyDataSource conn=new JREmptyDataSource(1);
    //Connection conn = getConnection("SpagoBI",getHttpSession(),profile,obj.getId().toString());      
    JRBeanCollectionDataSource datasource = new JRBeanCollectionDataSource(objNoteList);

    HashedMap parameters = new HashedMap();
    parameters.put("PARAM_OUTPUT_FORMAT", outputType);
    parameters.put("TITLE", executionInstance.getBIObject().getLabel());

    UUIDGenerator uuidGen = UUIDGenerator.getInstance();
    UUID uuid_local = uuidGen.generateTimeBasedUUID();
    String executionId = uuid_local.toString();
    executionId = executionId.replaceAll("-", "");
    //Creta etemp file
    String dirS = System.getProperty("java.io.tmpdir");
    File dir = new File(dirS);
    dir.mkdirs();
    String fileName = "notes" + executionId;
    OutputStream out = null;
    File tmpFile = null;
    try {
        tmpFile = File.createTempFile(fileName, "." + outputType, dir);
        out = new FileOutputStream(tmpFile);
        StringBufferInputStream sbis = new StringBufferInputStream(templateStr);
        logger.debug("compiling report");
        JasperReport report = JasperCompileManager.compileReport(sbis);
        //report.setProperty("", )
        logger.debug("filling report");
        JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, datasource);
        JRExporter exporter = null;
        if (outputType.equalsIgnoreCase("PDF")) {
            exporter = (JRExporter) Class.forName("net.sf.jasperreports.engine.export.JRPdfExporter")
                    .newInstance();
            if (exporter == null)
                exporter = new JRPdfExporter();
        } else {
            exporter = (JRExporter) Class.forName("net.sf.jasperreports.engine.export.JRRtfExporter")
                    .newInstance();
            if (exporter == null)
                exporter = new JRRtfExporter();
        }

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
        logger.debug("exporting report");
        exporter.exportReport();

    } catch (Throwable e) {
        logger.error("An exception has occured", e);
        return;
    } finally {
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error("Error closing output", e);
        }
    }

    String mimeType;
    if (outputType.equalsIgnoreCase("RTF")) {
        mimeType = "application/rtf";
    } else {
        mimeType = "application/pdf";
    }

    HttpServletResponse response = getHttpResponse();
    response.setContentType(mimeType);
    response.setHeader("Content-Disposition", "filename=\"report." + outputType + "\";");
    response.setContentLength((int) tmpFile.length());
    try {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
        int b = -1;
        while ((b = in.read()) != -1) {
            response.getOutputStream().write(b);
        }
        response.getOutputStream().flush();
        in.close();
    } catch (Exception e) {
        logger.error("Error while writing the content output stream", e);
    } finally {
        tmpFile.delete();
    }

    logger.debug("OUT");

}

From source file:it.eng.spagobi.engines.exporters.KpiExporter.java

public File getKpiReportPDF(List<KpiResourceBlock> kpiBlocks, BIObject obj, String userId) throws Exception {
    logger.debug("IN");

    //Build report template
    String docName = (obj != null) ? obj.getName() : "";
    BasicTemplateBuilder basic = new BasicTemplateBuilder(docName);
    String template2 = "";
    List templates = basic.buildTemplate(kpiBlocks);
    boolean first = true;

    //String template2=basic.buildTemplate(kpiBlocks);

    //System.out.println(template2);

    String outputType = "PDF";
    HashedMap parameters = new HashedMap();
    parameters.put("PARAM_OUTPUT_FORMAT", outputType);

    //parameters.put("SBI_HTTP_SESSION", session);   ???

    JREmptyDataSource conn = new JREmptyDataSource(1);

    // identity string for object execution
    UUIDGenerator uuidGen = UUIDGenerator.getInstance();
    UUID uuid_local = uuidGen.generateTimeBasedUUID();
    String executionId = uuid_local.toString();
    executionId = executionId.replaceAll("-", "");

    //Creta etemp file
    String dirS = System.getProperty("java.io.tmpdir");
    File dir = new File(dirS);
    dir.mkdirs();/*from   w w w  . ja v  a 2  s.  c o  m*/

    List filesToDelete = new ArrayList();
    logger.debug("Create Temp File");
    String fileName = "report" + executionId;
    File tmpFile = File.createTempFile(fileName, "." + outputType, dir);
    OutputStream out = new FileOutputStream(tmpFile);
    try {
        if (templates != null && !templates.isEmpty()) {
            int subreports = 0;
            Iterator it = templates.iterator();
            while (it.hasNext()) {
                String template = (String) it.next();
                if (first)
                    template2 = template;
                else {

                    File f = new File(dirS + File.separatorChar + "Detail" + subreports + ".jasper");
                    logger.debug("Compiling subtemplate file: " + f);
                    filesToDelete.add(f);

                    File file = new File(dirS + File.separatorChar + "Detail" + subreports + ".jrxml");
                    if (file.exists()) {
                        boolean deleted = file.delete();
                        file = new File(dirS + File.separatorChar + "Detail" + subreports + ".jrxml");
                    }
                    FileOutputStream stream = new FileOutputStream(file);
                    stream.write(template.getBytes());
                    stream.flush();
                    stream.close();
                    filesToDelete.add(file);

                    JasperCompileManager.compileReportToFile(
                            dirS + File.separatorChar + "Detail" + subreports + ".jrxml",
                            dirS + File.separatorChar + "Detail" + subreports + ".jasper");
                    subreports++;
                }
                first = false;
            }
        }

        File f = new File(dirS + File.separatorChar + "Master.jasper");
        logger.debug("Compiling subtemplate file: " + f);
        filesToDelete.add(f);

        File file = new File(dirS + File.separatorChar + "Master.jrxml");
        if (file.exists()) {
            boolean deleted = file.delete();
            file = new File(dirS + File.separatorChar + "Master.jrxml");
        }
        FileOutputStream stream = new FileOutputStream(file);
        stream.write(template2.getBytes());
        stream.flush();
        stream.close();
        filesToDelete.add(file);

        StringBufferInputStream sbis = new StringBufferInputStream(template2);
        JasperCompileManager.compileReportToFile(dirS + File.separatorChar + "Master.jrxml",
                dirS + File.separatorChar + "Master.jasper");

        logger.debug("Filling report ...");
        Context ctx = new InitialContext();
        Session aSession = HibernateUtil.currentSession();
        JasperPrint jasperPrint = null;
        try {
            Transaction tx = aSession.beginTransaction();
            //Connection jdbcConnection = aSession.connection();
            Connection jdbcConnection = HibernateUtil.getConnection(aSession);
            jasperPrint = JasperFillManager.fillReport(dirS + File.separatorChar + "Master.jasper", parameters,
                    jdbcConnection);
            logger.debug("Report filled succesfully");
        } finally {
            if (aSession != null) {
                if (aSession.isOpen())
                    aSession.close();
            }
        }
        logger.debug("Exporting report: Output format is [" + outputType + "]");
        JRExporter exporter = null;
        //JRExporter exporter = ExporterFactory.getExporter(outputType);   
        // Set the PDF exporter
        exporter = (JRExporter) Class.forName("net.sf.jasperreports.engine.export.JRPdfExporter").newInstance();

        if (exporter == null)
            exporter = new JRPdfExporter();

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
        exporter.exportReport();
        logger.debug("Report exported succesfully");
        //in = new BufferedInputStream(new FileInputStream(tmpFile));
        logger.debug("OUT");
        return tmpFile;

    } catch (Throwable e) {
        logger.error("An exception has occured", e);
        throw new Exception(e);
    } finally {
        out.flush();
        out.close();
        if (filesToDelete != null && !filesToDelete.isEmpty()) {
            Iterator it = filesToDelete.iterator();
            while (it.hasNext()) {
                File temp = (File) it.next();
                temp.delete();
            }
        }
        //tmpFile.delete();

    }

}

From source file:com.bmw.spdxeditor.editors.spdx.SPDXEditorUtility.java

/**
 * Get SPDXDocument as InputStream//  ww  w  .j av a2s . c  o  m
 * @param document
 * @return
 */
public static InputStream getModelInputStream(SPDXDocument document) {
    // Save document
    Model spdxFileModel = document.getModel();
    InputStream spdxDocumentInputStream = new StringBufferInputStream("");
    RDFReader r = spdxFileModel.getReader("RDF/XML");
    r.setProperty("attribtueQuoteChar", "'");
    r.setProperty("showXMLDeclaration", "true");
    r.setProperty("tab", "3");
    r.read(spdxFileModel, spdxDocumentInputStream, "");
    return spdxDocumentInputStream;
}

From source file:com.yahoo.ycsb.db.RedisClient.java

public static String decompress(String st) {
    if (compress != null && compress.equals("y")) {
        if (compressAlgo != null && (compressAlgo.equals("lz4") || compressAlgo.equals("lz4hc"))) {
            try {
                int split = st.indexOf('|');
                final int decompressedLength = Integer.parseInt(st.substring(0, split));
                LZ4FastDecompressor decompressor = lz4factory.fastDecompressor();
                byte[] restored = new byte[decompressedLength];
                byte[] compressed = st.substring(split + 1, st.length()).getBytes("ISO-8859-1");
                decompressor.decompress(compressed, 0, restored, 0, decompressedLength);
                String ret = new String(restored, "ISO-8859-1");
                return ret;
            } catch (Exception e) {
                e.printStackTrace();//from  ww  w .j a  v a 2 s.  c  o m
            }
        } else if (compressAlgo != null && compressAlgo.equals("bzip2")) {
            try {
                InputStream in = new StringBufferInputStream(st);
                BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(in);
                byte[] data = st.getBytes("ISO-8859-1");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int n = 0;
                while (-1 != (n = bzIn.read(data))) {
                    baos.write(data, 0, n);
                }
                bzIn.close();
                return baos.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (compressAlgo != null && compressAlgo.equals("snappy")) {
            try {
                byte[] uncompressed = Snappy.uncompress(st.getBytes("ISO-8859-1"));
                String ret = new String(uncompressed, "ISO-8859-1");
                return ret;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return st;
}

From source file:org.outermedia.solrfusion.adapter.solr.DefaultSolrAdapterTest.java

@Test
public void testErrorCase() throws URISyntaxException, IOException {
    DefaultSolrAdapter adapter = spy((DefaultSolrAdapter) DefaultSolrAdapter.Factory.getInstance());
    SearchServerConfig sc = new SearchServerConfig();
    sc.setUrl("http://localhost");
    adapter.init(sc);/*from w  ww .j  a  v  a  2s.  c  o  m*/
    CloseableHttpClient client = mock(CloseableHttpClient.class);
    HttpPost request = mock(HttpPost.class);
    CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    StatusLine sl = mock(StatusLine.class);
    HttpEntity entity = mock(HttpEntity.class);
    when(adapter.newHttpClient()).thenReturn(client);
    doReturn(request).when(adapter).newHttpPost(anyString(), any(SolrFusionUriBuilder.class));
    when(client.execute(request)).thenReturn(response);
    when(response.getStatusLine()).thenReturn(sl);
    when(sl.getStatusCode()).thenReturn(400);
    when(sl.getReasonPhrase()).thenReturn("Bad Query");
    when(response.getEntity()).thenReturn(entity);

    // without response
    when(entity.getContent()).thenReturn(null);
    Multimap<String> params = new Multimap<>();
    params.put(QUERY, "*:*");
    params.put(SORT, "score desc");
    try {
        SolrFusionUriBuilder ub = adapter.buildHttpClientParams(null, null, null, params, new Version("4.1"));
        adapter.sendQuery(ub, 2000);
        Assert.fail("Expected SearchServerResponseException for http status 400");
    } catch (SearchServerResponseException se) {
        String msg = se.getMessage();
        Assert.assertEquals("Expected other error message", "ERROR 400: Bad Query", msg);
    }

    // with response
    when(entity.getContent()).thenReturn(new StringBufferInputStream("Bad Content"));
    try {
        SolrFusionUriBuilder ub = adapter.buildHttpClientParams(null, null, null, params, new Version("4.1"));
        adapter.sendQuery(ub, 2000);
        Assert.fail("Expected SearchServerResponseException for http status 400");
    } catch (SearchServerResponseException se) {
        String msg = se.getMessage();
        Assert.assertEquals("Expected other error message", "ERROR 400: Bad Query", msg);
        Assert.assertNotNull("Response should be set", se.getHttpContent());
    }
}

From source file:de.avanux.livetracker.statistics.TrackingStatistics.java

private void setCountryCode(float lat, float lon) {
    Document doc = null;/* w  w w .j  a  v a  2 s  .  com*/
    HttpMethod method = null;
    InputStream responseBodyStream = null;
    String responseBodyString = null;
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        String uri = "http://www.geoplugin.net/extras/location.gp?lat=" + lat + "&long=" + lon + "&format=xml";
        log.debug("Retrieving country from " + uri);

        HttpClient client = new HttpClient();
        method = new GetMethod(uri);
        client.executeMethod(method);
        byte[] responseBodyBytes = method.getResponseBody();

        responseBodyString = new String(responseBodyBytes);
        log.debug("Content retrieved: " + responseBodyString);

        // the content is declared as UTF-8 but it seems to be iso-8859-1
        responseBodyString = new String(responseBodyBytes, "iso-8859-1");

        responseBodyStream = new StringBufferInputStream(responseBodyString);
        doc = builder.parse(responseBodyStream);

        XPath xpath = XPathFactory.newInstance().newXPath();
        this.countryCode = ((Node) xpath.evaluate("/geoPlugin/geoplugin_countryCode/text()", doc,
                XPathConstants.NODE)).getNodeValue();
        log.debug("countryCode=" + this.countryCode);
    } catch (Exception e) {
        if (responseBodyString != null) {
            log.error("unparsed xml=" + responseBodyString);
        }
        if (doc != null) {
            log.error("parsed xml=" + getDocumentAsString(doc));
        }
        log.error("Error getting country code.", e);
    } finally {
        try {
            if (responseBodyStream != null) {
                responseBodyStream.close();
            }
            if (method != null) {
                method.releaseConnection();
            }
        } catch (IOException e) {
            log.error("Error releasing resources: ", e);
        }
    }
}

From source file:com.wabacus.config.database.type.DB2.java

public void setClobValue(int iindex, String value, PreparedStatement pstmt) throws SQLException {
    if (value == null)
        value = "";
    StringBufferInputStream sbis = new StringBufferInputStream(value);
    pstmt.setAsciiStream(iindex, sbis, sbis.available());
}

From source file:com.novell.ldap.DsmlConnection.java

/**
 *Allows for a pre-build DSMLv2 Document to be sent over
 *the wire.  Usefull when doing batch requests
 * @param DSML The String version of the DSMLv2
 * @return List of results/*from  www .j a  v  a2s  .com*/
 * @throws LDAPException
 */
public ArrayList sendDoc(String DSML) throws LDAPException {
    ArrayList results = new ArrayList();
    try {
        PostMethod post = new PostMethod(serverString);
        //post.setDoAuthentication(true);

        //First load up the content headers
        post.setRequestHeader("Content-Type", "text/xml; charset=utf8");
        if (this.useSoap) {
            post.setRequestHeader("SOAPAction", "#batchRequest");
        }

        if (this.callback != null) {
            this.callback.manipulationPost(post, this);
        }

        StringWriter out = new StringWriter();

        PrintWriter pout = new PrintWriter(out);

        //First print the SOAP Envelope 
        pout.println("<?xml version=\"1.0\" encoding=\"UTF8\"?>");
        if (this.useSoap) {
            pout.println("<soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">");
            pout.println("<soap-env:Body>");
        }
        //write out the message
        //writer.writeMessage(message);
        //writer.finish();
        pout.write(DSML);

        if (this.useSoap) {
            //Complete the SOAP Envelope
            pout.println("</soap-env:Body>");
            pout.println("</soap-env:Envelope>");
        }
        StringBufferInputStream in = new StringBufferInputStream(out.toString());
        //Set the input stream

        post.setRequestBody(in);

        //POST the request
        con.executeMethod(post);

        DSMLReader reader = new DSMLReader(post.getResponseBodyAsStream());

        post.releaseConnection();

        //Make sure it was successfull
        /*LDAPException e = reader.
        if (e != null) throw e;*/

        ArrayList errors = reader.getErrors();
        if (errors.size() > 0) {
            throw ((LDAPException) errors.get(0));
        }

        LDAPMessage msg;
        while ((msg = reader.readMessage()) != null) {
            results.add(msg);
        }

    } catch (HttpException e) {
        throw new LDAPLocalException("Http Error", LDAPException.CONNECT_ERROR, e);
    } catch (IOException e) {
        throw new LDAPLocalException("Communications Error", LDAPException.CONNECT_ERROR, e);
    }

    return results;
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

/**
 * @param source/*from   w  w  w .ja v  a  2  s.  co  m*/
 * @return InputStream
 */
public static InputStream stripDoctype(InputStream source) {
    String result = getInputAsString(new InputStreamReader(source));

    Pattern docDeclPattern = Pattern.compile(DOC_DECL_PATTERN);
    Matcher docDeclMatcher = docDeclPattern.matcher(result);
    result = docDeclMatcher.replaceAll("");

    return new StringBufferInputStream(result);
}

From source file:edu.stanford.epad.epadws.queries.XNATQueries.java

public static String getXNATSubjectFieldValue(String sessionID, String xnatSubjectID, String fieldName) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(XNATQueryUtil.buildSubjectURL(xnatSubjectID) + "?format=xml");
    int xnatStatusCode;
    //log.info("Calling XNAT Subject info:" + XNATQueryUtil.buildSubjectURL(xnatSubjectID) + "?format=xml");
    method.setRequestHeader("Cookie", "JSESSIONID=" + sessionID);

    try {/*from   w  w w.j  a v  a 2s .  c o  m*/
        xnatStatusCode = client.executeMethod(method);
        String xmlResp = method.getResponseBodyAsString(10000);
        log.debug(xmlResp);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputStream is = new StringBufferInputStream(xmlResp);
        Document doc = db.parse(is);
        doc.getDocumentElement().normalize();
        NodeList nodes = doc.getElementsByTagName("xnat:field");
        String value = "";
        String subjfieldname = "";
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            value = node.getTextContent();
            if (value != null)
                value = value.replace('\n', ' ').trim();
            NamedNodeMap attrs = node.getAttributes();
            String attrName = null;
            for (int j = 0; attrs != null && j < attrs.getLength(); j++) {
                attrName = attrs.item(j).getNodeName();
                subjfieldname = attrs.item(j).getNodeValue();
                if (fieldName.equalsIgnoreCase(subjfieldname))
                    return value;
            }
        }
        return value;
    } catch (Exception e) {
        log.warning(
                "Warning: error performing XNAT subject query " + XNATQueryUtil.buildSubjectURL(xnatSubjectID),
                e);
        xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    } finally {
        method.releaseConnection();
    }
    return null;
}