Example usage for java.io StringWriter getBuffer

List of usage examples for java.io StringWriter getBuffer

Introduction

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

Prototype

public StringBuffer getBuffer() 

Source Link

Document

Return the string buffer itself.

Usage

From source file:edu.cornell.med.icb.goby.stats.TestAnnotationAveragingWriter.java

@Test
public void testCase1() {
    String[] samples = new String[] { "sample1" };
    int[] positions = new int[] { 5, 7 };
    int[][] C = { { 5, 3 } };
    int[][] Cm = { { 9, 8 } };
    testSupport = new MethylCountProviderTestSupport(samples, positions, "Case1", C, Cm);
    final StringWriter stringWriter = new StringWriter();
    AnnotationAveragingWriter testWriter = new AnnotationAveragingWriter(stringWriter, genome, testSupport);
    testWriter.setAnnotationFilename("test-data/vcf-averaging/annotations-1.tsv");
    testWriter.setContexts(DEFAULT_TEST_CONTEXTS);
    testWriter.setWriteNumSites(false);// ww w . j  a va2s .c  o  m
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.close();
    assertEquals("Test Case 1 result: ",
            "Chromosome\tStart\tEnd\tFeature\tMR[sample1][CpG]\tMR[sample1][CpA]\tMR[sample1][CpC]\tMR[sample1][CpT]\tMR[sample1][CpN]\n"
                    + "Case1\t4\t8\tannotation0\t68.00\t\t\t\t\n",
            stringWriter.getBuffer().toString());
}

From source file:jeplus.data.ParameterItem.java

public String toText() {
    Properties prop = new Properties();
    prop.setProperty("ID", ID);
    prop.setProperty("Name", Name);
    prop.setProperty("Type", Integer.toString(Type));
    prop.setProperty("Description", Description);
    prop.setProperty("SearchString", SearchString);
    prop.setProperty("ValuesString", ValuesString);
    StringWriter sw = new StringWriter();
    try {//from  ww  w. j a  va2  s. c  o m
        prop.store(sw, "Parameter item details");
    } catch (Exception ex) {
        logger.error("", ex);
        return null;
    }
    return sw.getBuffer().toString();
}

From source file:fr.gouv.finances.dgfip.xemelios.importers.DefaultImporter.java

protected void processTempFile(final File df, final String fileEncoding, final String xmlVersion,
        final String header, final String footer, final TDocument persistenceConfig, final Pair collectivite,
        final Pair codeBudget, final File originalFile, final int docCount, final boolean shouldDelete,
        final int progress) {
    try {//w w w  . j  av a  2s.  c o m
        long startFile = System.currentTimeMillis();
        String data = FileUtils.readTextFile(df, fileEncoding);
        StringBuilder fullText = new StringBuilder();
        fullText.append("<?xml version=\"").append(xmlVersion).append("\" encoding=\"").append(fileEncoding)
                .append("\"?>");
        fullText.append(header).append(data).append(footer);
        String sFullText = fullText.toString();
        byte[] bData = sFullText.getBytes(fileEncoding);

        Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(bData));

        // il faut retrouver de quel etat est ce document
        // on cherche si la balise root contient un
        // dm.getEtatxxx().getBalise()
        EtatModel currentEtat = null;
        for (EtatModel em : dm.getEtats()) {
            String balise = em.getBalise();
            NodeList nl = doc.getElementsByTagName(balise);
            if (nl.getLength() > 0) {
                currentEtat = em;
                break;
            } else {
                nl = doc.getElementsByTagNameNS(em.getBaliseNamespace(), balise);
                if (nl.getLength() > 0) {
                    currentEtat = em;
                    break;
                }
            }
        }
        // traitement d'erreur, on n'arrive pas  identifier l'etat
        if (currentEtat == null) {
            StringWriter sw = new StringWriter();
            sw.append("Impossible de dterminer l'tat de ce document :\n");
            TransformerFactory errorTransFactory = FactoryProvider.getTransformerFactory();
            Transformer errorTransformer = errorTransFactory.newTransformer();
            errorTransformer.transform(new DOMSource(doc), new StreamResult(sw));
            sw.flush();
            sw.close();
            logger.error(sw.getBuffer().toString());
            return;
        }
        // apply before-import xslt
        if (persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile() != null) {
            Transformer trans = importXsltCache
                    .get(persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile());
            if (trans == null) {
                TransformerFactory tf = FactoryProvider.getTransformerFactory();
                File directory = new File(currentEtat.getParent().getBaseDirectory());
                File xslFile = new File(directory,
                        persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile());
                trans = tf.newTransformer(new StreamSource(xslFile));
                importXsltCache.put(persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile(), trans);
            }
            // important, maintenant que c'est mis en cache !
            trans.reset();
            if (codeBudget != null) {
                trans.setParameter("CodeBudget", codeBudget.key);
                trans.setParameter("LibelleBudget", codeBudget.libelle);
            }
            if (collectivite != null) {
                trans.setParameter("CodeCollectivite", collectivite.key);
                trans.setParameter("LibelleCollectivite", collectivite.libelle);
            }
            if (getManifeste() != null) {
                trans.setParameter("manifeste", new DOMSource(getManifeste()));
            }
            // on passe en parametre le nom du fichier
            trans.setParameter("file.name", originalFile.getName());

            trans.setOutputProperty(OutputKeys.ENCODING, fileEncoding);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            trans.transform(new StreamSource(new ByteArrayInputStream(sFullText.getBytes(fileEncoding))),
                    new StreamResult(baos));
            bData = baos.toByteArray();
        }
        importTimingOS.append(originalFile.getName()).append(";").append(df.toURI().toURL().toExternalForm())
                .append(";XSL;").append(Long.toString(startFile)).append(";")
                .append(Long.toString(startFile = System.currentTimeMillis()));
        importTimingOS.println();

        String docName = StringUtilities.removeFileNameSuffix(originalFile.getName()) + "-" + docCount + "."
                + dm.getExtension();
        if (!isCancelled()) {
            try {
                if (!DataLayerManager.getImplementation().importElement(dm, currentEtat, codeBudget,
                        collectivite, originalFile.getName(), docName, bData, fileEncoding, getArchiveName(),
                        user)) {
                    logger.warn(DataLayerManager.getImplementation().getWarnings());
                    warningCount++;
                }
            } catch (DataAccessException daEx) {
                logger.error("importing element:", daEx);
                throw (Exception) daEx;
            } catch (DataConfigurationException dcEx) {
                logger.error("importing element:", dcEx);
                throw (Exception) dcEx.getCause();
            }
        }
        if (shouldDelete) {
            df.delete();
        }
        importTimingOS.append(originalFile.getName()).append(";").append(df.toURI().toURL().toExternalForm())
                .append(";IDX;").append(Long.toString(startFile)).append(";")
                .append(Long.toString(startFile = System.currentTimeMillis()));
        importTimingOS.println();
        this.getImpSvcProvider().pushCurrentProgress(progress);
    } catch (Exception ex) {
        //TODO
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.annotations.web.AnnotationExportControllerImplFastTest.java

@Test
public void testExportSearchResultsTabText() throws Exception {

    PrintWriter writer = null;//from  w  ww. j a v  a  2 s. c o m

    try {
        String viewName = annotationExportController.exportSearchResults(mockSession, modelMap, "tab");

        checkColumnHeadersAndAttributes();
        assertEquals("txt", viewName);
        assertEquals("tab", modelMap.get(ExportUtils.ATTRIBUTE_EXPORT_TYPE).toString());
        assertEquals("tcga_annotations.txt", modelMap.get(ExportUtils.ATTRIBUTE_FILE_NAME));

        StringWriter stringWriter = new StringWriter();
        //noinspection IOResourceOpenedButNotSafelyClosed
        writer = new PrintWriter(stringWriter);

        // check to make sure we can use the BeanToTextExporter on the resulting object
        String output = BeanToTextExporter.beanListToText("tab", writer,
                (Map<String, String>) modelMap.get(ExportUtils.ATTRIBUTE_COLUMN_HEADERS),
                (List) modelMap.get(ExportUtils.ATTRIBUTE_DATA),
                (DateFormat) modelMap.get(ExportUtils.ATTRIBUTE_DATE_FORMAT));
        writer.close();
        assertEquals(
                "ID\tDisease\tItem Type\tItem Barcode\tAnnotation Classification\tAnnotation Category\tAnnotation Notes\tDate Created\tCreated By\tStatus\n"
                        + "123\tdis1; dis2\ttype1; type2\titem1; item2\tthis is a classification\tthis is a category\tthis is my note1; this is my note2\t04/14/2011\tme\tApproved\n",
                stringWriter.getBuffer().toString());
        assertFalse(output.equals("An error occurred."));
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:org.apache.cayenne.modeler.dialog.ErrorDebugDialog.java

protected void setThrowable(Throwable throwable) {
    this.throwable = throwable;

    String text = null;//from  w w w .j  a v a2 s. c om
    if (throwable != null) {
        StringWriter str = new StringWriter();
        PrintWriter out = new PrintWriter(str);

        // first add extra diagnostics
        String version = LocalizedStringsHandler.getString("cayenne.version");
        version = (version != null) ? version : "(unknown)";

        String buildDate = LocalizedStringsHandler.getString("cayenne.build.date");
        buildDate = (buildDate != null) ? buildDate : "(unknown)";

        out.println("CayenneModeler Info");
        out.println("Version: " + version);
        out.println("Build Date: " + buildDate);
        out.println("Exception: ");
        out.println("=================================");
        buildStackTrace(out, throwable);

        try {
            out.close();
            str.close();
        } catch (IOException ioex) {
            // this should never happen
        }
        text = str.getBuffer().toString();
    }

    exText.setText(text);
}

From source file:net.sourceforge.seqware.pipeline.deciders.BasicDecider.java

protected void printFileMetadata(ReturnValue file, FileMetadata fm) {
    String studyName = (String) options.valueOf("study-name");
    try {/* ww  w  .  ja  v  a 2s  .c  o m*/
        StringWriter writer = new StringWriter();
        FindAllTheFiles.print(writer, file, studyName, true, fm);
        studyReporterOutput.add(writer.getBuffer().toString().trim());
    } catch (IOException ex) {
        Log.error("Error printing file metadata", ex);
    }
}

From source file:com.aimluck.eip.project.util.ProjectUtils.java

/**
 * ?????/*from w  w  w  . ja v  a2s. co  m*/
 * 
 * @return
 */
public static String createProjectMemberMsg(RunData rundata, String addr, EipTProject project) {
    VelocityContext context = new VelocityContext();
    boolean enableAsp = JetspeedResources.getBoolean("aipo.asp", false);
    String CR = ALMailUtils.CR;

    context.put("user_email", addr);

    // ??????????
    StringBuffer message = new StringBuffer("");
    message.append(CR);
    message.append(getl10nFormat("PROJECT_MAIL_TEXT2", project.getProjectName())).append(CR);
    context.put("message", message);

    // 
    context.put("serviceAlias", ALOrgUtilsService.getAlias());
    // Aipo??
    context.put("enableAsp", enableAsp);
    context.put("globalurl", ALMailUtils.getGlobalurl());
    context.put("localurl", ALMailUtils.getLocalurl());
    CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil
            .getServiceByName(LocalizationService.SERVICE_NAME);
    String lang = locService.getLocale(rundata).getLanguage();
    StringWriter writer = new StringWriter();
    try {
        if (lang != null && lang.equals("ja")) {
            Template template = Velocity.getTemplate("portlets/mail/" + lang + "/project-notification-mail.vm",
                    "utf-8");
            template.merge(context, writer);
        } else {
            Template template = Velocity.getTemplate("portlets/mail/project-notification-mail.vm", "utf-8");
            template.merge(context, writer);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    writer.flush();
    String ret = writer.getBuffer().toString();
    return ret;

}

From source file:com.aimluck.eip.project.util.ProjectUtils.java

/**
 * ?????//from   w ww .j av a2 s .  c o  m
 * 
 * @return
 */
public static String createTaskMemberMsg(RunData rundata, String addr, EipTProjectTask task,
        EipTProject project) {
    VelocityContext context = new VelocityContext();
    boolean enableAsp = JetspeedResources.getBoolean("aipo.asp", false);
    String CR = ALMailUtils.CR;

    context.put("user_email", addr);

    // ??????????
    StringBuffer message = new StringBuffer("");
    message.append(CR);
    message.append(getl10nFormat("PROJECT_MAIL_TEXT", project.getProjectName(), task.getTaskName())).append(CR);
    context.put("message", message);

    // 
    context.put("serviceAlias", ALOrgUtilsService.getAlias());
    // Aipo??
    context.put("enableAsp", enableAsp);
    context.put("globalurl", ALMailUtils.getGlobalurl());
    context.put("localurl", ALMailUtils.getLocalurl());
    CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil
            .getServiceByName(LocalizationService.SERVICE_NAME);
    String lang = locService.getLocale(rundata).getLanguage();
    StringWriter writer = new StringWriter();
    try {
        if (lang != null && lang.equals("ja")) {
            Template template = Velocity.getTemplate("portlets/mail/" + lang + "/project-notification-mail.vm",
                    "utf-8");
            template.merge(context, writer);
        } else {
            Template template = Velocity.getTemplate("portlets/mail/project-notification-mail.vm", "utf-8");
            template.merge(context, writer);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    writer.flush();
    String ret = writer.getBuffer().toString();
    return ret;

}

From source file:io.nosorog.core.ScriptLoader.java

/**
 * Load a {@link Script} from {@link InputStream}.
 * @param is stream to read from/*from   w  w w. j a  v a2 s.  co  m*/
 * @return script object
 * @throws IOException if IOException has occurred while reading from the stream
 * @throws ScriptException if an error occurred while processing imports or injections
 */
public Script load(InputStream is) throws IOException, ScriptException {

    StringWriter body = new StringWriter();
    PrintWriter pw = new PrintWriter(body);

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {

        String line;
        boolean flag = false;
        Collection<Node> nodes = new ArrayList<>();

        while ((line = reader.readLine()) != null) {

            pw.println(line);

            if (StringUtils.strip(line).equals("/**")) {
                flag = true;
                continue;
            }

            if (StringUtils.strip(line).equals("*/")) {
                flag = false;
                continue;
            }

            if (flag) {
                try {
                    Node node = parseHeader(line);
                    if (node != null) {
                        nodes.add(node);
                    }
                } catch (ParseException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }
            }

        }

        return Script.builder(nodes, body.getBuffer().toString(), classLoader).build();

    }

}

From source file:net.sf.jasperreports.engine.export.JRXmlExporter.java

/**
 *
 *///  ww w  .  j a  v a2  s  . c om
protected StringBuffer exportReportToBuffer() throws JRException {
    StringWriter buffer = new StringWriter();
    try {
        exportReportToStream(buffer);
    } catch (IOException e) {
        throw new JRException("Error while exporting report to buffer", e);
    }
    return buffer.getBuffer();
}