Example usage for java.io Writer toString

List of usage examples for java.io Writer toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.infoscoop.web.CustomizationServlet.java

private String applyFreemakerTemplate(Map<String, Object> root, String value) {
    try {/*ww w. java2  s . c  o m*/

        Writer out = new StringWriter();
        Template t = new Template("portalLayout_template", new StringReader(value), cfg);

        t.setTemplateExceptionHandler(new TemplateExceptionHandler() {
            public void handleTemplateException(TemplateException templateexception, Environment environment,
                    Writer writer) {
                log.error("--- templete error occurred", templateexception);
            }
        });
        t.process(root, out);

        return out.toString();
    } catch (freemarker.core.ParseException e) {
        log.error("--- templete error occurred", e);
    } catch (TemplateException e) {
        log.error("--- templete error occurred", e);
    } catch (IOException e) {
        log.error("--- templete error occurred", e);
    }
    return value;
}

From source file:com.glaf.dts.transform.MxTransformManager.java

protected void transformMany(QueryDefinition query, TableDefinition target) {
    logger.debug("------------------------------transformMany--------------");
    if (!StringUtils.equals(query.getTargetTableName(), target.getTableName())) {
        return;//w w  w.jav  a  2 s . co m
    }
    if (query.getParent() != null && query.getParent().getResultList() != null
            && !query.getParent().getResultList().isEmpty()) {
        int execution = 0;
        logger.debug("#####################################################");
        logger.debug("execution count:" + query.getParent().getResultList().size());

        List<TransformTask> tasks = new java.util.ArrayList<TransformTask>();
        List<String> taskIds = new java.util.ArrayList<String>();
        for (Map<String, Object> paramMap : query.getParent().getResultList()) {
            execution++;
            TransformTask task = new TransformTask();
            task.setId(query.getId() + "_exec_" + execution);
            task.setStatus(0);
            task.setQueryId(query.getId());
            task.setTableName(query.getTargetTableName());
            task.setTitle(query.getTitle() + "  " + execution);
            task.setSortNo(execution);
            JsonFactory f = new JsonFactory();
            ObjectMapper mapper = new ObjectMapper(f);
            Writer w = new StringWriter();
            try {
                mapper.writeValue(w, paramMap);
                task.setParameter(w.toString());
            } catch (Exception e) {
                task.setParameter(JsonUtils.encode(paramMap));
            }
            tasks.add(task);
            taskIds.add(task.getId());
        }

        transformTaskService.insertAll(query.getId(), tasks);

        if (taskIds.size() > 0) {

        }
    }
}

From source file:com.wxxr.mobile.core.tools.VelocityTemplateRenderer.java

@Override
public String renderFromFile(String templateFilename, Map<String, Object> attributes) {
    checkWasConfigured();//from ww  w . j av  a2  s  .  co  m
    customize(false);

    try {
        logger.info("Retrieving template: {}", templateFilename);

        VelocityContext context = createContext(attributes);

        TypeUtils typeUtils = createTypeUtils();
        context.put("types", typeUtils);

        Writer writer = new StringWriter();

        File file = new File(templateFilename);
        if (file.exists()) {
            Reader reader = new FileReader(file);
            engine.evaluate(context, writer, templateFilename, reader);
        } else {
            Template t = engine.getTemplate(templateFilename);
            t.merge(context, writer);
        }
        String renderedText = writer.toString();

        return postProcess(renderedText, typeUtils);
    } catch (Exception e) {
        String report = String.format("Rendering of template '%s' failed", templateFilename);
        throw new RuntimeException(report, e);
    }
}

From source file:ca.twoducks.vor.ossindex.report.Assistant.java

/** Export the data in JSON format
 * //from   ww  w .  j a  v a 2s . co  m
 * @return
 */
@SuppressWarnings("unused")
private String exportJson() {
    Writer writer = new StringWriter();
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    gson.toJson(config, writer);

    return writer.toString();
}

From source file:com.google.livingstories.servlet.DataImportServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    startTime = System.currentTimeMillis();

    message = "";

    if (req.getContentType().contains("multipart/form-data")) {
        try {/*w  w w. j a  v a2  s  . com*/
            ServletFileUpload upload = new ServletFileUpload();
            JSONObject data = null;
            boolean override = false;
            FileItemIterator iter = upload.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (item.getFieldName().equals("override")) {
                    override = true;
                } else if (item.getFieldName().equals("data")) {
                    data = new JSONObject(Streams.asString(item.openStream()));
                }
            }
            checkRunState(override);
            inputData = data;
            setUp();
        } catch (FileUploadException ex) {
            throw new RuntimeException(ex);
        } catch (JSONException ex) {
            throw new RuntimeException(ex);
        }
    }

    try {
        process();
    } catch (Exception ex) {
        Writer result = new StringWriter();
        PrintWriter printWriter = new PrintWriter(result);
        ex.printStackTrace(printWriter);
        message = result.toString();
        runState = RunState.ERROR;
    } finally {
        if (runState != RunState.RUNNING) {
            tearDown();
        }
        Caches.clearAll();
    }

    resp.setContentType("text/html");
    resp.getWriter().append(message + "<br>" + runState.name());
}

From source file:org.jannocessor.service.render.VelocityTemplateRenderer.java

@Override
public String renderFromFile(String templateFilename, Map<String, Object> attributes)
        throws JannocessorException {
    checkWasConfigured();// w w  w .  ja v a  2 s  . c o  m
    customize(false);

    try {
        logger.info("Retrieving template: {}", templateFilename);

        VelocityContext context = createContext(attributes);

        TypeUtils typeUtils = createTypeUtils();
        context.put("types", typeUtils);

        Writer writer = new StringWriter();

        File file = new File(templateFilename);
        if (file.exists()) {
            Reader reader = new FileReader(file);
            engine.evaluate(context, writer, templateFilename, reader);
        } else {
            Template t = engine.getTemplate(templateFilename);
            t.merge(context, writer);
        }
        String renderedText = writer.toString();

        return postProcess(renderedText, typeUtils);
    } catch (Exception e) {
        String report = String.format("Rendering of template '%s' failed", templateFilename);
        throw new JannocessorException(report, e);
    }
}

From source file:gov.nih.nci.cabig.caaers.api.AdeersReportGeneratorTest.java

public void testImage() throws Exception {

    generator.setAdverseEventReportSerializer(new AdverseEventReportSerializer());
    generator.setEvaluationService(evaluationService);
    String xmlFileName = "expedited_report_caaers_complete.xml";
    InputStream is = AdeersReportGeneratorTest.class.getClassLoader().getResourceAsStream(xmlFileName);
    Writer writer = new StringWriter();
    if (is != null) {
        char[] buffer = new char[1024];
        try {/* ww w .  ja  v  a  2  s  .  co m*/
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
            reader.close();
        } finally {
            is.close();
        }
    }

    String caAERSXML = writer.toString();

    //System.out.println(caAERSXML);
    long now = System.currentTimeMillis();
    String fileName = System.getProperty("java.io.tmpdir") + File.separator + "ae" + String.valueOf(now)
            + "report.png";
    List<String> list = generator.generateImage(caAERSXML, fileName);

}

From source file:de.dfki.iui.mmds.dialogue.DialogueComponent.java

@Override
public void resetCurrentScxmlContext() {
    Context currentContext = stateMachine.getCurrentContext();
    List<String> activeStates = stateMachine.getAllActiveStates();
    for (String stateId : activeStates) {
        AbstractState node = idToDialogueNode.get(stateId);
        for (Variable variable : node.getVariables()) {
            Object defaultValue = null;
            if (variable.getDefault() != null && !variable.getDefault().isEmpty()) {
                if (variable.getEmfType() != null && variable.getEmfType() instanceof EDataType) {
                    defaultValue = variable.getEmfType().getEPackage().getEFactoryInstance()
                            .createFromString((EDataType) variable.getEmfType(), variable.getDefault());
                } else if (variable.getType() != null && !variable.getType().isEmpty()) {
                    try {
                        defaultValue = stateMachine.siamEvaluator.eval(currentContext, variable.getDefault());
                    } catch (IllegalArgumentException | SecurityException | SCXMLExpressionException e) {
                        final Writer result = new StringWriter();
                        final PrintWriter printWriter = new PrintWriter(result);
                        e.printStackTrace(printWriter);
                        Logger.getLogger(this.getClass()).warn(String.format(
                                "Cannot create default variable value \"%s\" for variable \"%s\" of type %s!\n%s",
                                variable.getDefault(), variable.getName(), variable.getType(),
                                result.toString()));
                    }/*  w  ww.ja v  a2s .  co m*/
                    if (defaultValue == null) {
                        Logger.getLogger(this.getClass()).warn(String.format(
                                "Cannot create default variable value \"%s\" for variable \"%s\" of type %s!",
                                variable.getDefault(), variable.getName(), variable.getType()));
                    }
                } else {
                    Logger.getLogger(this.getClass()).warn(String.format(
                            "Cannot create default value for variable \"%s\". The type %s is not serializable.",
                            variable.getName(), variable.getEmfType()));
                }
            }
            //            currentContext.set(name, value);
            currentContext.set(variable.getName(), defaultValue);
        }
    }
}

From source file:se.kb.oai.pmh.OaiPmhServer.java

private Document executeQuery(String query) throws OAIException, IOException {
    LOGGER.info(" --->  Sending query to OAI-PMH-server: ---> \n {}", query);
    if (this.client == null) {
        // if there is no special client initialized use the default one
        try {// w ww.  ja  v a 2s.  c  om
            return this.reader.read(query);
        } catch (DocumentException e) {
            LOGGER.error("Problem parsing OAI-PMH result from query {}", query);
            throw new OAIException("", e);
        }
    } else {
        HttpGet httpget = new HttpGet(query);
        HttpResponse response = this.client.execute(httpget);
        String message = "";
        try {
            InputStream en = response.getEntity().getContent();

            if (en != null) {
                Writer writer = new StringWriter();
                char[] buffer = new char[1024];
                try {
                    Reader reader = new BufferedReader(new InputStreamReader(en, Charsets.UTF_8));
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, n);
                        message = writer.toString();
                    }
                } finally {
                    en.close();
                }
            }

            StringReader sr = new StringReader(message);
            LOGGER.info("<--- Received result from OAI-PMH-server: <---\n {}", message);
            return this.reader.read(sr);
        } catch (DocumentException de) {
            LOGGER.error("Problem parsing OAI-PMH result from query {} with result {}", query, message);
            throw new OAIException("", de);
        }
    }
}

From source file:com.xpn.xwiki.internal.template.TemplateManager.java

public String renderFromSkin(String template, Skin skin) throws Exception {
    Writer writer = new StringWriter();

    renderFromSkin(template, skin, writer);

    return writer.toString();
}