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:com.krawler.portal.tools.ServiceBuilder.java

public static void writeFile(File file, String content, String author, Map<String, Object> jalopySettings)
        throws IOException {

    String packagePath = "com/krawler/esp/hibernate/impl";//_getPackagePath(file);

    String className = file.getName();

    className = className.substring(0, className.length() - 5);

    content = SourceFormatter.stripImports(content, packagePath, className);

    File tempFile = new File("ServiceBuilder.temp");
    Writer output = new BufferedWriter(new FileWriter(tempFile));
    output.write(content);//from   w  w  w .ja  va  2 s . co  m
    output.close();
    StringBuffer sb = new StringBuffer();
    Jalopy jalopy = new Jalopy();
    jalopy.setFileFormat(FileFormat.UNIX);
    jalopy.setInput(tempFile);
    jalopy.setOutput(sb);
    //      try {
    //         Jalopy.setConvention("../tools/jalopy.xml");
    //      }
    //      catch (FileNotFoundException fnne) {
    //                    System.out.print(fnne.getMessage());
    //      }
    //      try {
    //         Jalopy.setConvention("../../misc/jalopy.xml");
    //      }
    //      catch (FileNotFoundException fnne) {
    //                    System.out.print(fnne.getMessage());
    //      }
    if (jalopySettings == null) {
        jalopySettings = new HashMap<String, Object>();
    }

    Environment env = Environment.getInstance();

    // Author

    author = GetterUtil.getString((String) jalopySettings.get("author"), author);

    env.set("author", author);

    // File name

    env.set("fileName", file.getName());

    Convention convention = Convention.getInstance();

    String classMask = "/**\n" + " * <a href=\"$fileName$.html\"><b><i>View Source</i></b></a>\n" + " *\n"
            + " * @author $author$\n" + " *\n" + "*/";

    convention.put(ConventionKeys.COMMENT_JAVADOC_TEMPLATE_CLASS, env.interpolate(classMask));

    convention.put(ConventionKeys.COMMENT_JAVADOC_TEMPLATE_INTERFACE, env.interpolate(classMask));

    jalopy.format();

    String newContent = sb.toString();

    /*
    // Remove blank lines after try {
            
    newContent = StringUtil.replace(newContent, "try {\n\n", "try {\n");
            
    // Remove blank lines after ) {
            
    newContent = StringUtil.replace(newContent, ") {\n\n", ") {\n");
            
    // Remove blank lines empty braces { }
            
    newContent = StringUtil.replace(newContent, "\n\n\t}", "\n\t}");
            
    // Add space to last }
            
    newContent = newContent.substring(0, newContent.length() - 2) + "\n\n}";
    */

    // Write file if and only if the file has changed

    String oldContent = null;

    if (file.exists()) {

        // Read file
        Reader reader = new BufferedReader(new FileReader(file));
        CharBuffer cbuf = new CharBuffer(reader);
        oldContent = cbuf.toString();
        reader.close();

        // Keep old version number

        int x = oldContent.indexOf("@version $Revision:");

        if (x != -1) {
            int y = oldContent.indexOf("$", x);
            y = oldContent.indexOf("$", y + 1);

            String oldVersion = oldContent.substring(x, y + 1);

            newContent = com.krawler.portal.util.StringUtil.replace(newContent, "@version $Rev: $", oldVersion);
        }
    } else {
        //         newContent = com.krawler.portal.util.StringUtil.replace(
        //            newContent, "@version $Rev: $", "@version $Revision: 1.183 $");
        file.createNewFile();
    }

    if (oldContent == null || !oldContent.equals(newContent)) {
        output = new BufferedWriter(new FileWriter(file));
        output.write(content);
        output.close();
        //         FileUtil.write(file, newContent);

        System.out.println("Writing " + file);

        // Workaround for bug with XJavaDoc

        file.setLastModified(System.currentTimeMillis() - (Time.SECOND * 5));
    }

    tempFile.deleteOnExit();
}

From source file:com.sun.faban.harness.webclient.Uploader.java

/**
 * Updates the run description./* w w  w. jav  a2  s . c o m*/
 * @param req
 * @param resp
 * @throws java.io.IOException
 */
public void updateRunDesc(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String runId = req.getParameter("runId");
    RunResult result = RunResult.getInstance(new RunId(runId));
    result.description = req.getParameter("desc");
    ResultAction.editXML(result);
    Writer w = resp.getWriter();
    w.write("Tags updating completed");
    w.flush();
    w.close();
}

From source file:com.silverpeas.jcrutil.model.impl.AbstractJcrTestCase.java

protected void createTempFile(String path, String content) throws IOException {
    File attachmentFile = new File(path);
    if (!attachmentFile.getParentFile().exists()) {
        attachmentFile.getParentFile().mkdirs();
    }/*from w  ww . j  ava  2s.c om*/
    FileOutputStream out = null;
    Writer writer = null;
    try {
        out = new FileOutputStream(attachmentFile);
        writer = new OutputStreamWriter(out);
        writer.write(content);
    } finally {
        if (writer != null) {
            writer.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:bammerbom.ultimatecore.bukkit.configuration.FileConfiguration.java

/**
 * Saves this {@link FileConfiguration} to the specified location.
 * <p/>/*from   w  w  w .  j  a  v a2 s .c  o m*/
 * If the file does not exist, it will be created. If already exists, it
 * will be overwritten. If it cannot be overwritten or created, an exception
 * will be thrown.
 * <p/>
 * This method will save using the system default encoding, or possibly
 * using UTF8.
 *
 * @param file File to save to.
 * @throws IOException Thrown when the given file cannot be written to for
 * any reason.
 * @throws IllegalArgumentException Thrown when file is null.
 */
public void save(File file) throws IOException {
    Validate.notNull(file, "File cannot be null");

    Files.createParentDirs(file);

    String data = saveToString();

    Writer writer = new OutputStreamWriter(new FileOutputStream(file),
            UTF8_OVERRIDE && !UTF_BIG ? Charsets.UTF_8 : Charset.defaultCharset());

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

From source file:ca.uhn.fhir.rest.method.BaseOutcomeReturningMethodBinding.java

protected void streamOperationOutcome(BaseServerResponseException theE, RestfulServer theServer,
        EncodingEnum theEncodingNotNull, HttpServletResponse theResponse, RequestDetails theRequest)
        throws IOException {
    theResponse.setStatus(theE.getStatusCode());

    theServer.addHeadersToResponse(theResponse);

    if (theE.getOperationOutcome() != null) {
        theResponse.setContentType(theEncodingNotNull.getResourceContentType());
        IParser parser = theEncodingNotNull.newParser(theServer.getFhirContext());
        parser.setPrettyPrint(RestfulServerUtils.prettyPrintResponse(theServer, theRequest));
        Writer writer = theResponse.getWriter();
        try {/*from  w  ww  .j  a v  a 2s  .c  om*/
            parser.encodeResourceToWriter(theE.getOperationOutcome(), writer);
        } finally {
            writer.close();
        }
    } else {
        theResponse.setContentType(Constants.CT_TEXT);
        Writer writer = theResponse.getWriter();
        try {
            writer.append(theE.getMessage());
        } finally {
            writer.close();
        }
    }
}

From source file:com.isencia.passerelle.runtime.repos.impl.filesystem.FlowRepositoryServiceImpl.java

/**
 * @param flowCode/*from  www . j  a  v  a 2s.  c  o  m*/
 * @param flowMetaDataProps
 * @throws IOException
 */
private void writeMetaData(String flowCode, Properties flowMetaDataProps) throws IOException {
    File flowRootFolder = new File(rootFolder, flowCode);
    File metaDataFile2 = new File(flowRootFolder, ".metadata");
    Writer metaDataWriter = new FileWriter(metaDataFile2);
    try {
        flowMetaDataProps.store(metaDataWriter, flowCode);
    } finally {
        metaDataWriter.close();
    }
}

From source file:com.netxforge.oss2.config.ThresholdingConfigFactory.java

/**
 * Saves the current in-memory configuration to disk and reloads
 *
 * @throws org.exolab.castor.xml.MarshalException if any.
 * @throws java.io.IOException if any.//from  www.  j av  a2 s .  c o m
 * @throws org.exolab.castor.xml.ValidationException if any.
 */
public synchronized void saveCurrent() throws MarshalException, IOException, ValidationException {
    // Marshal to a string first, then write the string to the file. This
    // way the original config
    // isn't lost if the XML from the marshal is hosed.
    StringWriter stringWriter = new StringWriter();
    Marshaller.marshal(m_config, stringWriter);

    String xmlString = stringWriter.toString();
    if (xmlString != null) {
        File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.THRESHOLDING_CONF_FILE_NAME);

        Writer fileWriter = new OutputStreamWriter(new FileOutputStream(cfgFile), "UTF-8");
        fileWriter.write(xmlString);
        fileWriter.flush();
        fileWriter.close();
    }

    update();

}

From source file:solidstack.reflect.Dumper.java

public void dumpTo(Object o, File file) {
    try {/*w ww.ja  va 2s  .co  m*/
        Writer out = new FileWriter(file);
        try {
            dumpTo(o, out);
        } finally {
            out.close();
        }
    } catch (IOException e) {
        throw Java.throwUnchecked(e);
    }
}

From source file:com.wavemaker.runtime.module.ModuleController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String requestURI = request.getRequestURI();
    final String moduleURI = "/" + MODULES_PREFIX;
    final String moduleURIAbs = moduleURI + "/";
    final String moduleJsURI = moduleURIAbs + MODULES_JS;
    final String epURI = moduleURIAbs + EXTENSION_PATH;
    final String epURIAbs = epURI + "/";
    final String idURI = moduleURIAbs + ID_PATH;
    final String idURIAbs = idURI + "/";

    // trim off the servlet name
    requestURI = requestURI.substring(requestURI.indexOf('/', 1));

    if (moduleURI.equals(requestURI) || moduleURIAbs.equals(requestURI)) {
    } else if (epURI.equals(requestURI) || epURIAbs.equals(requestURI)) {
        Set<String> names = this.moduleManager.listExtensionPoints();

        response.setContentType("text/html");
        Writer writer = response.getWriter();
        writer.write("<html><body>\n");
        for (String ext : names) {
            writer.write(ext + "<br />\n");
        }/*  ww  w  .  j  a  v  a  2  s. c o m*/
        writer.write("</body></html>\n");
        writer.close();
    } else if (idURI.equals(requestURI) || idURIAbs.equals(requestURI)) {
        Set<String> names = this.moduleManager.listModules();

        response.setContentType("text/html");
        Writer writer = response.getWriter();
        writer.write("<html><body>\n");
        for (String ext : names) {
            writer.write(ext + "<br />\n");
        }
        writer.write("</body></html>\n");
        writer.close();
    } else if (moduleJsURI.equals(requestURI)) {
        Set<String> extensions = this.moduleManager.listExtensionPoints();

        JSONObject jo = new JSONObject();

        JSONObject extJO = new JSONObject();
        for (String extension : extensions) {
            JSONArray ja = new JSONArray();

            List<ModuleWire> wires = this.moduleManager.getModules(extension);
            for (ModuleWire wire : wires) {
                ja.add(wire.getName());
            }

            extJO.put(extension, ja);
        }

        jo.put("extensionPoints", extJO);

        response.setContentType(ServerConstants.JSON_CONTENT_TYPE);
        Writer writer = response.getWriter();
        writer.write(jo.toString());
        writer.close();
    } else {
        Tuple.Two<ModuleWire, String> tuple = parseRequestPath(requestURI);
        if (tuple.v1 == null) {
            String message = MessageResource.NO_MODULE_RESOURCE.getMessage(requestURI, tuple.v2);
            this.logger.error(message);

            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Writer outputWriter = response.getWriter();
            outputWriter.write(message);

            return null;
        }

        URL url = this.moduleManager.getModuleResource(tuple.v1, tuple.v2);
        URLConnection conn = url.openConnection();
        if (SystemUtils.IS_OS_WINDOWS) {
            conn.setDefaultUseCaches(false);
        }

        response.setContentType(conn.getContentType());
        OutputStream os = null;
        InputStream is = null;

        try {
            os = response.getOutputStream();
            is = conn.getInputStream();

            IOUtils.copy(conn.getInputStream(), os);
        } finally {
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        }
    }

    return null;
}

From source file:doc.doclets.WorkbenchHelpDoclet.java

private static String _generateClassLevelDocumentation(ClassDoc classDoc, String actorHelpTemplate)
        throws Exception {
    Writer resultWriter = new StringWriter();
    try {//  w  w  w  .j a v  a 2s .  c  o  m
        Context velocityContext = new VelocityContext();
        velocityContext.put("actorName", _generateShortClassName(classDoc));
        velocityContext.put("actorClassName", _generateClassName(classDoc));
        velocityContext.put("allDocElements", _generateClassLevelDocumentationElements(classDoc));
        velocityContext.put("actorClassDoc", _inlineTagCommentText(classDoc));
        velocityContext.put("allActorAttributes",
                _generateActorAttributeElements(classDoc, Class.forName("ptolemy.data.expr.Parameter")));

        velocity.evaluate(velocityContext, resultWriter, "actor help template", actorHelpTemplate);
        return resultWriter.toString();
    } finally {
        try {
            resultWriter.close();
        } catch (Exception e) {
        }
    }
}