Example usage for java.io Writer close

List of usage examples for java.io Writer close

Introduction

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

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream, flushing it first.

Usage

From source file:io.github.jeddict.jcode.parser.ejs.EJSParser.java

public Consumer<FileTypeStream> getParserManager(List<String> skipFile) {
    return (fileType) -> {
        try {//from   w  ww .  java  2 s  .  c o m
            if (SKIP_FILE_TYPE.contains(fileType.getFileType())
                    || (skipFile != null && skipFile.contains(fileType.getFileName()))
                    || fileType.isSkipParsing()) {
                IOUtils.copy(fileType.getInputStream(), fileType.getOutputStream());
                if (!(fileType.getInputStream() instanceof ZipInputStream)) {
                    fileType.getInputStream().close();
                }
                fileType.getOutputStream().close();
            } else {
                Charset charset = Charset.forName("UTF-8");
                Reader reader = new BufferedReader(new InputStreamReader(fileType.getInputStream(), charset));
                Writer writer = new BufferedWriter(new OutputStreamWriter(fileType.getOutputStream(), charset));
                IOUtils.write(parse(reader), writer);
                if (!(fileType.getInputStream() instanceof ZipInputStream)) {
                    reader.close();
                }
                writer.flush();
                writer.close();
            }

        } catch (ScriptException | IOException ex) {
            Exceptions.printStackTrace(ex);
            System.out.println("Error in template : " + fileType.getFileName());
        }
    };
}

From source file:com.googlecode.jsfFlexPlugIn.parser.velocity.JsfFlexVelocityParser.java

public synchronized void mergeCollectionToTemplate(String template, Map<String, Object> contextInfo,
        Writer targetWriter, String fileMerged) {

    for (String currKey : contextInfo.keySet()) {
        _context.put(currKey, contextInfo.get(currKey));
    }//from  w w w.  j av  a2  s  .c o  m

    try {
        _velocityEngine.mergeTemplate(template, _context, targetWriter);
        targetWriter.flush();

    } catch (Exception exceptionWhileMerging) {
        throw new RuntimeException(exceptionWhileMerging);
    } finally {
        try {
            if (targetWriter != null) {
                targetWriter.close();
            }
        } catch (IOException closerException) {
            _log.debug("Error in closing the writer within mergeCollectionToTemplate", closerException);
        }
    }

    mergeCollectionToTemplateFinished(fileMerged);
}

From source file:edu.cornell.med.icb.goby.modes.ExtractSplicingEventsMode.java

@Override
public void execute() throws IOException {
    Writer output = null;
    final boolean consoleOutput = outputFilename.equals("-");
    if (consoleOutput) {
        output = new OutputStreamWriter(System.out);
    } else {/*w  w w. j  a v  a  2 s  .co m*/
        output = new FileWriter(outputFilename);
    }

    for (String filename : inputFilenames) {
        ExportSplicingEvents processor = new ExportSplicingEvents(output);
        processor.setMinMappingQuality(qualThreshold);
        processor.process(filename);

    }
    if (!consoleOutput) {
        output.close();
    }
}

From source file:gz.aws.blog.feed.RomeResult.java

/**
 * Implementation of {@link org.apache.struts2.dispatcher.StrutsResultSupport#doExecute(String, com.opensymphony.xwork2.ActionInvocation)}
 *
 * @param location         final location (jsp page, action, etc)
 * @param actionInvocation the ActionInvocation
 * @throws Exception/*from  ww  w.  j a v  a2  s.  c om*/
 */
public void doExecute(String location, ActionInvocation actionInvocation) throws Exception {
    if (feedName == null) {
        // ack, we need this to find the feed on the stack, if not, blow up
        final String message = "Required parameter 'feedName' not found. "
                + "Make sure you have the param tag set and "
                + "the staticParams interceptor enabled in your interceptor stack.";
        logger.error(message); // log it in case the runtime exception gets swallowed
        throw new RuntimeException(message); // no point in continuing ..
    }

    // don't forget to set the content to the correct mimetype
    ServletActionContext.getResponse().setContentType(mimeType);
    // get the feed from the stack that can be found by the feedName
    SyndFeed feed = (SyndFeed) actionInvocation.getStack().findValue(feedName);
    if (feed != null) {
        if (encoding == null)
            encoding = feed.getEncoding(); // second choice is whatever the feed specifies
        if (encoding != null)
            ServletActionContext.getResponse().setCharacterEncoding(encoding);
        // If neither of the above work, we'll get the platform default.

        if (logger.isDebugEnabled())
            logger.debug("Found object on stack with expression '" + feedName + "': " + feed);

        if (feedType != null) // if the feedType is specified, we'll override the one set in the feed object
            feed.setFeedType(feedType);

        SyndFeedOutput output = new SyndFeedOutput();
        // we'll need the writer since Rome doesn't support writing to an outputStream yet

        Writer out = null;
        try {
            out = ServletActionContext.getResponse().getWriter();
            output.output(feed, out);
        } catch (Exception e) {
            // Woops, couldn't write the feed ?
            logger.error("Could not write the feed: " + e.getMessage(), e);
        } finally {
            // close the output writer (will flush automatically)
            if (out != null)
                out.close();
        }
    } else {
        // woops .. no object found on the stack with that name ?
        final String message = "Did not find object on stack with name '" + feedName + "'";
        logger.error(message);
        throw new RuntimeException(message); // no point in continuing ..
    }
}

From source file:com.github.sqltojava.JavaGenerator.java

private void generateJava() {
    Properties p = new Properties();
    p.setProperty("resource.loader", "string");
    p.setProperty("resource.loader.class", "org.apache.velocity.runtime.resource.loader.StringResourceLoader");
    Velocity.init(p);/*from  w  ww . ja va  2 s  .  com*/

    Template template = getTemplate("sample.vm");

    Iterator<String> tableKey = tables.keySet().iterator();
    while (tableKey.hasNext()) {
        String tableName = tableKey.next();
        String className = tableName.substring(0, 1).toUpperCase()
                + tableName.substring(1).replaceFirst("(^.*?)@.*", "$1");
        VelocityContext context = new VelocityContext();
        context.put("className", className);
        context.put("tableName", tableName.replaceFirst("(^.*?)@(.*)", "$2"));
        context.put("columns", columns.get(tableName));
        context.put("outPackage", outPackage);
        try {
            String outDirs = basedir + "/" + outPackage.replaceAll("\\.", "/");
            new File(outDirs).mkdirs();
            Writer writer = new OutputStreamWriter(new FileOutputStream(outDirs + "/" + className + ".java"),
                    "utf-8");
            template.merge(context, writer);
            writer.flush();
            writer.close();
        } catch (IOException ex) {
            getLog().log(Level.WARNING, ex.getMessage(), ex);
        }
    }
}

From source file:com.glaf.jbpm.web.springmvc.MxJbpmCompleteTaskController.java

@RequestMapping
public ModelAndView completeTask(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug(paramMap);/*w ww .  j a  va2s.  c  o m*/
    String json = RequestUtils.getStringValue(request, "json");
    Long processInstanceId = ParamUtils.getLong(paramMap, "processInstanceId");
    Long taskInstanceId = ParamUtils.getLong(paramMap, "taskInstanceId");
    String transitionName = RequestUtils.getStringValue(request, "transitionName");
    String jumpToNode = RequestUtils.getStringValue(request, "jumpToNode");
    String isAgree = RequestUtils.getStringValue(request, "isAgree");
    String opinion = RequestUtils.getStringValue(request, "opinion");
    logger.debug("json:" + json);
    logger.debug("processInstanceId:" + processInstanceId);
    logger.debug("taskInstanceId:" + taskInstanceId);
    logger.debug("transitionName:" + transitionName);
    logger.debug("jumpToNode:" + jumpToNode);
    logger.debug("isAgree:" + isAgree);
    logger.debug("opinion:" + opinion);
    String actorId = RequestUtils.getActorId(request);
    ProcessContainer container = ProcessContainer.getContainer();
    String processName = null;
    boolean canSubmit = false;
    boolean isOK = false;
    TaskItem taskItem = null;
    if ("0".equals(isAgree)) {
        isAgree = "false";
    } else if ("1".equals(isAgree)) {
        isAgree = "true";
    }

    if (taskInstanceId != null && StringUtils.isNotEmpty(actorId)) {
        /**
         * ????
         */
        taskItem = container.getTaskItem(taskInstanceId, actorId);
        if (taskItem != null) {
            if (processInstanceId != null) {
                canSubmit = true;
                processInstanceId = taskItem.getProcessInstanceId();
                processName = taskItem.getProcessName();
            }
        }
    } else if (processInstanceId != null && StringUtils.isNotEmpty(actorId)) {
        /**
         * ?????
         */
        taskItem = container.getMinTaskItem(actorId, processInstanceId);
        if (taskItem != null) {
            canSubmit = true;
            processName = taskItem.getProcessName();
        }
    }

    /**
     * ???
     */
    if (canSubmit && taskItem != null) {
        ProcessContext ctx = new ProcessContext();
        /**
         * ??json?.<br>
         * {money:100000,day:5,pass:true,deptId:"123", roleId:"R001"}
         */
        if (StringUtils.isNotEmpty(json)) {
            Map<String, Object> jsonMap = JsonUtils.decode(json);
            if (jsonMap != null && jsonMap.size() > 0) {
                Set<Entry<String, Object>> entrySet = jsonMap.entrySet();
                for (Entry<String, Object> entry : entrySet) {
                    String name = entry.getKey();
                    Object value = entry.getValue();
                    if (name != null && value != null) {
                        DataField dataField = new DataField();
                        dataField.setName(name);
                        dataField.setValue(value);
                        ctx.addDataField(dataField);
                    }
                }
            }
        }

        DataField dataField = new DataField();
        dataField.setName("isAgree");
        dataField.setValue(isAgree);
        ctx.addDataField(dataField);

        ctx.setActorId(actorId);
        ctx.setOpinion(opinion);
        ctx.setProcessInstanceId(taskItem.getProcessInstanceId());
        ctx.setTaskInstanceId(taskItem.getTaskInstanceId());
        ctx.setJumpToNode(jumpToNode);
        ctx.setTransitionName(transitionName);

        try {
            isOK = container.completeTask(ctx);
            request.setAttribute("isOK", Boolean.valueOf(isOK));
            if (isOK) {
                request.setAttribute("statusCode", 200);
                request.setAttribute("message", ViewProperties.getString("res_submit_ok"));
            } else {
                request.setAttribute("statusCode", 500);
                request.setAttribute("message", ViewProperties.getString("res_submit_error"));
            }
        } catch (Exception ex) {
            request.setAttribute("statusCode", 500);
            request.setAttribute("message", ViewProperties.getString("res_submit_error"));
            if (LogUtils.isDebug()) {
                ex.printStackTrace();
                logger.debug(ex);
            }
        }
    }

    String responseDataType = RequestUtils.getStringValue(request, "responseDataType");
    /**
     * ??jsonxml???<br>
     * 200-? <br>
     * 500-<br>
     */
    if (StringUtils.equals(responseDataType, "json")) {
        String encoding = request.getParameter("encoding");
        if (encoding == null) {
            encoding = "UTF-8";
        }
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType("text/plain;charset=" + encoding);
        Map<String, Object> jsonMap = new java.util.HashMap<String, Object>();
        if (isOK) {
            jsonMap.put("statusCode", 200);
            jsonMap.put("success", "true");
            jsonMap.put("data", ViewProperties.getString("res_submit_ok"));
            jsonMap.put("message", ViewProperties.getString("res_submit_ok"));
        } else {
            jsonMap.put("statusCode", 500);
            jsonMap.put("success", "false");
            jsonMap.put("data", ViewProperties.getString("res_submit_error"));
            jsonMap.put("message", ViewProperties.getString("res_submit_error"));
        }
        JSONObject object = new JSONObject(jsonMap);
        Writer writer = response.getWriter();
        writer.write(object.toString());
        writer.flush();
        writer.close();
        writer = null;
        return null;
    } else if (StringUtils.equals(responseDataType, "xml")) {
        String encoding = request.getParameter("encoding");
        if (encoding == null) {
            encoding = "UTF-8";
        }
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType("text/xml;charset=" + encoding);
        StringBuffer buffer = new StringBuffer();
        buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        buffer.append("<response>");
        if (isOK) {
            buffer.append("\n    <statusCode>200</statusCode>");
            buffer.append("\n    <message>").append(ViewProperties.getString("res_submit_ok"))
                    .append("</message>");
        } else {
            buffer.append("\n    <statusCode>500</statusCode>");
            buffer.append("\n    <message>").append(ViewProperties.getString("res_submit_error"))
                    .append("</message>");
        }
        buffer.append("\n</response>");
        Writer writer = response.getWriter();
        writer.write(buffer.toString());
        writer.flush();
        writer.close();
        writer = null;
        return null;
    }

    /**
     * ?????<br>
     * ?????_complete_template??jbpm_complete_template
     * WEB-INF\conf\extension??
     */
    String templateId = RequestUtils.getStringValue(request, "y_templateId");
    if (StringUtils.isEmpty(templateId)) {
        templateId = CustomProperties.getString(processName + "_complete_template");
    }
    if (StringUtils.isEmpty(templateId)) {
        templateId = CustomProperties.getString("jbpm_complete_template");
    }
    if (StringUtils.isNotEmpty(templateId)) {

        Map<String, Object> context = new java.util.HashMap<String, Object>();
        context.putAll(paramMap);
        context.put("actorId", actorId);
        context.put("canSubmit", canSubmit);
        context.put("isOK", isOK);
        context.put("taskItem", taskItem);
        context.put("processInstanceId", processInstanceId);
        context.put("contextPath", request.getContextPath());

        if (isOK) {
            context.put("statusCode", 200);
            context.put("message", ViewProperties.getString("res_submit_ok"));
        } else {
            context.put("statusCode", 500);
            context.put("message", ViewProperties.getString("res_submit_error"));
        }
        try {
            logger.debug(context);
            Writer writer = new StringWriter();
            TemplateUtils.evaluate(templateId, context, writer);
            request.setAttribute("templateScript", writer.toString());
            String encoding = request.getParameter("encoding");
            if (encoding == null) {
                encoding = "UTF-8";
            }
            request.setCharacterEncoding(encoding);
            response.setCharacterEncoding(encoding);
            response.setContentType("text/html;charset=" + encoding);
            response.getWriter().write(writer.toString());
            return null;
        } catch (Exception ex) {
            if (LogUtils.isDebug()) {
                ex.printStackTrace();
                logger.debug(ex);
            }
        }
    }

    String jx_view = request.getParameter("jx_view");

    if (StringUtils.isNotEmpty(jx_view)) {
        return new ModelAndView(jx_view);
    }

    String x_view = ViewProperties.getString("jbpm_complete.complateTask");
    if (StringUtils.isNotEmpty(x_view)) {
        return new ModelAndView(x_view);
    }

    return new ModelAndView("/jbpm/complete");
}

From source file:gov.va.vinci.chartreview.util.CRSchemaXML.java

private void finalizeRender(Writer out) {
    try {//  w  w w.ja  v  a2 s .c om
        if (out != null) {
            out.flush();
            out.close();
        }
    } catch (Exception e) {
        log.warn("Unexpected exception while closing a writer: " + e.getMessage());
    }
}

From source file:com.agiletec.plugins.jprss.apsadmin.rss.RomeResult.java

/**
 * Implementation of {@link org.apache.struts2.dispatcher.StrutsResultSupport#doExecute(String, com.opensymphony.xwork2.ActionInvocation)}
 * @param location final location (jsp page, action, etc)
 * @param actionInvocation the ActionInvocation
 * @throws Exception/*from  w w  w  . j  a v  a2s. c om*/
 */
@Override
public void doExecute(String location, ActionInvocation actionInvocation) throws Exception {
    if (feedName == null) {
        // ack, we need this to find the feed on the stack, if not, blow up
        final String message = "Required parameter 'feedName' not found. "
                + "Make sure you have the param tag set and "
                + "the staticParams interceptor enabled in your interceptor stack.";
        logger.error(message); // log it in case the runtime exception gets swallowed
        throw new RuntimeException(message); // no point in continuing ..
    }

    // don't forget to set the content to the correct mimetype
    ServletActionContext.getResponse().setContentType(mimeType);
    // get the feed from the stack that can be found by the feedName
    SyndFeed feed = (SyndFeed) actionInvocation.getStack().findValue(feedName);

    if (feed != null) {
        if (encoding == null)
            encoding = feed.getEncoding(); // second choice is whatever the feed specifies
        if (encoding != null)
            ServletActionContext.getResponse().setCharacterEncoding(encoding);
        // If neither of the above work, we'll get the platform default.

        if (logger.isDebugEnabled())
            logger.debug("Found object on stack with expression '" + feedName + "': " + feed);

        if (feedType != null) // if the feedType is specified, we'll override the one set in the feed object
            feed.setFeedType(feedType);

        SyndFeedOutput output = new SyndFeedOutput();
        // we'll need the writer since Rome doesn't support writing to an outputStream yet
        Writer out = null;
        try {
            out = ServletActionContext.getResponse().getWriter();
            output.output(feed, out);
        } catch (Exception e) {
            // Woops, couldn't write the feed ?
            logger.error("Could not write the feed: " + e.getMessage(), e);
        } finally {
            // close the output writer (will flush automatically)
            if (out != null)
                out.close();
        }
    } else {
        // woops .. no object found on the stack with that name ?
        final String message = "Did not find object on stack with name '" + feedName + "'";
        logger.error(message);
        throw new RuntimeException(message); // no point in continuing ..
    }
}

From source file:com.enjoyxstudy.selenium.autoexec.CommandHandler.java

/**
 * text to response./* www  .jav a 2 s  . co m*/
 *
 * @param response
 * @param text
 * @param type
 * @throws IOException
 */
private void toResponse(HttpResponse response, String text, String type) throws IOException {

    if (type.equals(TYPE_TEXT)) {
        // text
        response.setContentType(CONTENT_TYPE_TEXT);
    } else {
        // json
        response.setContentType(CONTENT_TYPE_JSON);
    }

    Writer writer = getResponceWriter(response);

    try {
        writer.write(text);
    } finally {
        writer.close();
    }
}

From source file:com.clican.pluto.orm.dynamic.impl.DynamicORMManagePojoHibernateImpl.java

private void generate(String file, Template template, VelocityContext velocityContext)
        throws ORMManageException {
    Writer w = null;
    try {// w  ww . j a  v  a  2 s.  com
        w = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
        template.merge(velocityContext, w);
        w.flush();
    } catch (Exception e) {
        throw new ORMManageException(e);
    } finally {
        try {
            if (w != null) {
                w.close();
            }
        } catch (Exception e) {
            log.error("", e);
        }
    }
}