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:edu.fullerton.viewerplugin.PluginSupport.java

/**
 * Create a Scalable Vector Graphics (SVG) file from a JFree Chart
 * @param chart the plot ready for saving
 * @param filename the output filename//from w ww  .  j  a  v  a 2s .co  m
 * @throws WebUtilException 
 */
public void saveImageAsSvgFile(JFreeChart chart, String filename) throws WebUtilException {
    // THE FOLLOWING CODE BASED ON THE EXAMPLE IN THE BATIK DOCUMENTATION...
    // Get a DOMImplementation
    DOMImplementation domImpl;
    domImpl = SVGDOMImplementation.getDOMImplementation();

    // Create an instance of org.w3c.dom.Document
    Document document = domImpl.createDocument(null, "svg", null);
    // Create an instance of the SVG Generator
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
    // set the precision to avoid a null pointer exception in Batik 1.5
    svgGenerator.getGeneratorContext().setPrecision(6);
    // Ask the chart to render into the SVG Graphics2D implementation
    chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height), null);
    // Finally, stream out SVG to a file using UTF-8 character to
    // byte encoding
    boolean useCSS = true;
    Writer out;
    try {
        out = new OutputStreamWriter(new FileOutputStream(new File(filename)), "UTF-8");
        svgGenerator.stream(out, useCSS);
        out.close();
    } catch (IOException ex) {
        throw new WebUtilException("Writing SVG image", ex);
    }
}

From source file:com.dsh105.nexus.hook.github.GitHub.java

public String createGist(Exception e) {
    Nexus.LOGGER.info("Creating a Gist for " + e.getClass().getName());
    Writer writer = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    e.printStackTrace(printWriter);// w ww.j a  va  2  s.c om
    Gist gist = new Gist(new GistFile(writer.toString()));
    try {
        writer.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return gist.create();
}

From source file:net.duckling.ddl.web.controller.LynxEditPageController.java

private void writeToResponse(HttpServletResponse response, String xml) {
    response.setContentType("text/html;charset=UTF-8");
    try {/*w  w w .  j a va2  s .c  o  m*/
        Writer wr = response.getWriter();
        wr.write(xml);
        wr.close();
    } catch (IOException e) {
        LOG.debug("Write xml to response error!", e);
    }
}

From source file:com.graphhopper.jsprit.io.problem.VrpXMLWriter.java

public void write(String filename) {
    if (!filename.endsWith(".xml"))
        filename += ".xml";
    log.info("write vrp: " + filename);
    XMLConf xmlConfig = new XMLConf();
    xmlConfig.setFileName(filename);/* w  w w.j av a  2  s  .c  om*/
    xmlConfig.setRootElementName("problem");
    xmlConfig.setAttributeSplittingDisabled(true);
    xmlConfig.setDelimiterParsingDisabled(true);

    writeProblemType(xmlConfig);
    writeVehiclesAndTheirTypes(xmlConfig);

    //might be sorted?
    List<Job> jobs = new ArrayList<Job>();
    jobs.addAll(vrp.getJobs().values());
    for (VehicleRoute r : vrp.getInitialVehicleRoutes()) {
        jobs.addAll(r.getTourActivities().getJobs());
    }

    writeServices(xmlConfig, jobs);
    writeShipments(xmlConfig, jobs);

    writeInitialRoutes(xmlConfig);
    if (onlyBestSolution && solutions != null) {
        VehicleRoutingProblemSolution solution = Solutions.bestOf(solutions);
        solutions.clear();
        solutions.add(solution);
    }

    writeSolutions(xmlConfig);

    OutputFormat format = new OutputFormat();
    format.setIndenting(true);
    format.setIndent(5);

    try {
        Document document = xmlConfig.createDoc();

        Element element = document.getDocumentElement();
        element.setAttribute("xmlns", "http://www.w3schools.com");
        element.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        element.setAttribute("xsi:schemaLocation", "http://www.w3schools.com vrp_xml_schema.xsd");

    } catch (ConfigurationException e) {
        throw new RuntimeException(e);
    }

    try {
        Writer out = new FileWriter(filename);
        XMLSerializer serializer = new XMLSerializer(out, format);
        serializer.serialize(xmlConfig.getDocument());
        out.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:it.crs4.seal.demux.Demux.java

private void createLaneContentFiles(Path outputPath, Path sampleSheetPath) throws IOException {
    StringBuilder builder = new StringBuilder(100);

    try {//from   ww w  . jav  a  2s  .  c  om
        Path qualifiedPath = sampleSheetPath.makeQualified(sampleSheetPath.getFileSystem(getConf()));
        SampleSheet sheet = DemuxUtils.loadSampleSheet(qualifiedPath, getConf());
        Collection<String> samples = sheet.getSamples();
        // we have one output directory per sample, thus we need one LaneContent file per sample.
        for (String sample : samples) {
            Writer out = makeLaneContentWriter(outputPath, sample);
            try {
                for (int lane = 1; lane <= 8; ++lane) {
                    builder.delete(0, builder.length());
                    builder.append(lane - 1).append(":");
                    if (sheet.getSamplesInLane(lane).contains(sample))
                        builder.append(sample);
                    builder.append("\n");
                    out.write(builder.toString());
                }
            } finally {
                out.close();
            }
        }
    } catch (SampleSheet.FormatException e) {
        throw new RuntimeException("Error in sample sheet.  " + e.getMessage());
    }
}

From source file:dk.defxws.fgssolrremote.OperationsImpl.java

private StringBuffer sendToSolr(String solrCommand, String postParameters) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("sendToSolr solrCommand=" + solrCommand + "\nPost parameters=\n" + postParameters);
    String base = config.getIndexBase(indexName);
    URI uri = new URI(base + solrCommand);
    URL url = uri.toURL();/*  ww  w .ja v a 2  s.c om*/
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    if (postParameters != null) {
        con.setRequestProperty("Content-type", "text/xml; charset=UTF-8");
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        OutputStream out = con.getOutputStream();
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        Reader reader = new StringReader(postParameters);
        char[] buf = new char[1024];
        int read = 0;
        while ((read = reader.read(buf)) >= 0) {
            writer.write(buf, 0, read);
        }
        writer.flush();
        writer.close();
        out.close();
    }

    int responseCode = con.getResponseCode();
    if (logger.isDebugEnabled())
        logger.debug("sendToSolr solrCommand=" + solrCommand + " response Code=" + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    if (logger.isDebugEnabled())
        logger.debug("sendToSolr solrCommand=" + solrCommand + "\n response=" + response);
    return response;
}

From source file:gr.omadak.leviathan.asp.AspParser.java

/**
* Parses an asp file and generates a List with the AST forest produced.
* @param file is the file to parse/* ww w.  j a  v a  2s. c  o m*/
* @param isVb indicates if the default language is VbScript
* @param sTable is an instance of SymbolTableExposer. If the file
* parsed is part of an include statement, then the parameter is not null,
* otherwise is expected to be null.
* @return a List which contains the AST forest if preserveAST is true.
*/
private List parseFile(File file, boolean isVb, SymbolTableExposer sTable) throws ANTLRException {
    List result;
    if (fileIsParsed(file)) {
        if (sTable != null) { //is an include file
            mergeSymbols((DataHolder) parsedFiles.get(file.getAbsolutePath()), sTable);
        }
        result = Collections.EMPTY_LIST;
    } else {
        currentFileName = file.getName();
        AspStreamSelector selector = new AspStreamSelector(file, baseDir, sTable == null);
        VbsParser vbParser = null;
        JsParser jsParser = null;
        VbsTree vbtree = null;
        JsTree jsTree = null;
        selector.setDefaultVb(isVb);
        result = new ArrayList();
        Set includes = null;
        if (generateCode) {
            includes = new HashSet();
        }
        DataHolder holder = new DataHolder();
        if (sTable != null) {
            fillHolder(sTable, holder);
        }
        while (selector.hasMoreTokens()) {
            if (selector.isVbCurrent()) {
                if (vbParser == null) {
                    vbParser = new VbsParser(selector);
                }
                vbParser.start_rule();
                AST node = vbParser.getAST();
                // new antlr.DumpASTVisitor().visit(node);
                if (node != null) {
                    if (vbtree == null) {
                        vbtree = new VbsTree();
                        vbtree.setAspParser(this);
                        vbtree.setFunctions(vbParser.getFunctions());
                        vbtree.setClasses(vbParser.getClasses());
                        vbtree.setGlobalIds(vbParser.getGlobalIds());
                        if (sTable != null) {
                            mergeSymbols(holder, sTable);
                        }
                    }
                    vbtree.start_rule(node);
                    if (generateCode) {
                        includes.addAll(vbtree.getDependencies());
                    }
                    fillHolder(vbtree, holder);
                    result.add(new Object[] { Boolean.TRUE, node, vbtree.getAST() });
                }
            } else {
                if (jsParser == null) {
                    jsParser = new JsParser(selector);
                }
                jsParser.start_rule();
                AST node = jsParser.getAST();
                if (node != null) {
                    //new antlr.DumpASTVisitor().visit(node);
                    if (jsTree == null) {
                        jsTree = new JsTree();
                        jsTree.setAspParser(this);
                        jsTree.setFunctions(jsParser.getFunctions());
                        jsTree.setAnonymousFunctions(jsParser.getAnonymousFunctions());
                        jsTree.setParserClasses(jsParser.getClasses());
                        if (sTable != null) {
                            mergeSymbols(holder, jsTree);
                        }
                    }
                    jsTree.start_rule(node);
                    if (generateCode) {
                        includes.addAll(jsTree.getDependencies());
                    }
                    fillHolder(jsTree, holder);
                    result.add(new Object[] { Boolean.FALSE, node, jsTree.getAST() });
                }
            }
        }
        if (preserveAST) {
            if (parsedAST == null) {
                parsedAST = new HashMap();
            }
            parsedAST.put(file.getAbsolutePath(), result);
        }
        if (parsedFiles == null) {
            parsedFiles = new HashMap();
        }
        parsedFiles.put(file.getAbsolutePath(), holder);
        if (generateCode) {
            try {
                Writer writer = getWriter(file);
                produceCode(result, writer, includes, file.getAbsolutePath());
                writer.close();
            } catch (IOException ioex) {
                LOG.error("Failed to generate code", ioex);
            }
        }
        if (sTable != null) {
            mergeSymbols(holder, sTable);
        }
    }
    return result;
}