Example usage for java.io Writer flush

List of usage examples for java.io Writer flush

Introduction

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

Prototype

public abstract void flush() throws IOException;

Source Link

Document

Flushes the stream.

Usage

From source file:ca.simplegames.micro.utils.IO.java

/**
 * Copy the contents of the given Reader to the given Writer.
 * Closes both when done./*from   w w  w .jav  a  2s.c  o m*/
 *
 * @param in  the Reader to copy from
 * @param out the Writer to copy to
 * @return the number of characters copied
 * @throws IOException in case of I/O errors
 */
public static int copy(Reader in, Writer out) throws IOException {
    try {
        int byteCount = 0;
        char[] buffer = new char[BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
            byteCount += bytesRead;
        }
        out.flush();
        return byteCount;
    } finally {
        IO.close(out);
        IO.close(in);
    }
}

From source file:net.officefloor.plugin.web.http.server.HttpServerAutoWireOfficeFloorSourceTest.java

/**
 * Writes the response./*  www. jav  a 2  s .  co  m*/
 * 
 * @param response
 *            Response.
 * @param connection
 *            {@link ServerHttpConnection}.
 */
private static void writeResponse(String response, ServerHttpConnection connection) throws IOException {
    Writer writer = new OutputStreamWriter(connection.getHttpResponse().getEntity());
    writer.append(response);
    writer.flush();
}

From source file:net.sf.nmedit.jsynth.clavia.nordmodular.utils.NmUtils.java

public static void writePatch(NMPatch patch, OutputStream out) throws IOException, ParseException {
    Writer writer = new BufferedWriter(new OutputStreamWriter(out, getPatchFileCharset()));
    try {/*from ww  w .ja  v a2  s  .  c  om*/
        (new PatchExporter()).export(patch, new PatchFileWriter(writer));
    } finally {
        writer.flush();
        writer.close();
    }
}

From source file:org.crazydog.util.spring.FileCopyUtils.java

/**
 * Copy the contents of the given Reader to the given Writer.
 * Closes both when done./* w  w  w .  j  a  v  a 2  s .c o m*/
 * @param in the Reader to copy from
 * @param out the Writer to copy to
 * @return the number of characters copied
 * @throws IOException in case of I/O errors
 */
public static int copy(Reader in, Writer out) throws IOException {
    org.springframework.util.Assert.notNull(in, "No Reader specified");
    org.springframework.util.Assert.notNull(out, "No Writer specified");
    try {
        int byteCount = 0;
        char[] buffer = new char[BUFFER_SIZE];
        int bytesRead = -1;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
            byteCount += bytesRead;
        }
        out.flush();
        return byteCount;
    } finally {
        try {
            in.close();
        } catch (IOException ex) {
        }
        try {
            out.close();
        } catch (IOException ex) {
        }
    }
}

From source file:com.cisco.dvbu.ps.common.scriptutil.ScriptUtil.java

/**
 * Create the Composite Studio Enable VCS property file.  The property file name is of the format <composite_user>.<domain>.<composite_server_host>.properties.
 * @param vcsIncludeResourceSecurity - the value is either "true" or "false"
 * @param vcsWorkspacePathOverride - this is a way of overriding the vcs workspace path.  The vcsWorkspacePath is derived from the studio.properties file properties:
 *                                   VCS_WORKSPACE_DIR+"/"+VCS_PROJECT_ROOT.  It will use the substitute drive by default.
 * @param vcsScriptBinFolderOverride - this is the bin folder name only for PDTool Studio.  Since PDTool Studio can now support multiple hosts via multiple /bin folders,
 *                             it is optional to pass in the /bin folder location.  e.g. bin_host1, bin_host2.  The default will be bin if the input is null or blank.                                 
 * @param studioPropertyName - the name of the PDTool configuration property file.  The default is studio.properties
 * @param PDToolHomeDir - the directory of the PDToolStudio home directory
 * @param propertyFilePath - this is the full path to the output file.  For windows 7 the location will be in %USERPROFILE%\.compositesw
 * //from w  ww  .  j a  v a  2 s  .  co  m
 * usage createStudioEnableVCSPropertyFile true studio.properties D/:/CompositeSoftware/CIS6.2.0/conf/studio/PDToolStudio62 C:/Users/mike/.compositesw/admin.composite.localhost.properties
 */
public static void createStudioEnableVCSPropertyFile(String vcsIncludeResourceSecurity,
        String vcsWorkspacePathOverride, String vcsScriptBinFolderOverride, String studioPropertyName,
        String PDToolHomeDir, String propertyFilePath) {

    String prefix = "createStudioEnableVCSPropertyFile";
    // Set the global suppress and debug properties used throughout this class
    String validOptions = "true,false";
    // Get the property from the property file
    String debug = CommonUtils.getFileOrSystemPropertyValue(studioPropertyName, "DEBUG1");
    boolean debug1 = false;
    if (debug != null && validOptions.contains(debug)) {
        debug1 = Boolean.valueOf(debug);
    }

    if (!vcsIncludeResourceSecurity.equals("true") && !vcsIncludeResourceSecurity.equals("false")) {
        throw new ApplicationException(
                "The variable vcsIncludeResourceSecurity may only be set to \"true\" or \"false\"");
    }
    if (vcsWorkspacePathOverride != null)
        vcsWorkspacePathOverride = vcsWorkspacePathOverride.trim();

    if (vcsScriptBinFolderOverride != null)
        vcsScriptBinFolderOverride = vcsScriptBinFolderOverride.trim();

    CommonUtils.writeOutput("", prefix, "-debug1", logger, debug1, false, false);
    CommonUtils.writeOutput("--- INPUT PARAMETERS ----", prefix, "-debug1", logger, debug1, false, false);
    CommonUtils.writeOutput("", prefix, "-debug1", logger, debug1, false, false);
    CommonUtils.writeOutput("    vcsIncludeResourceSecurity=" + vcsIncludeResourceSecurity, prefix, "-debug1",
            logger, debug1, false, false);
    CommonUtils.writeOutput("    vcsWorkspacePathOverride=[" + vcsWorkspacePathOverride + "]  len="
            + vcsWorkspacePathOverride.length(), prefix, "-debug1", logger, debug1, false, false);
    CommonUtils.writeOutput("    vcsScriptFolderOverride=[" + vcsScriptBinFolderOverride + "]  len="
            + vcsScriptBinFolderOverride.length(), prefix, "-debug1", logger, debug1, false, false);
    CommonUtils.writeOutput("    studioPropertyName=" + studioPropertyName, prefix, "-debug1", logger, debug1,
            false, false);
    CommonUtils.writeOutput("    PDToolHomeDir=" + PDToolHomeDir, prefix, "-debug1", logger, debug1, false,
            false);
    CommonUtils.writeOutput("    propertyFilePath=" + propertyFilePath, prefix, "-debug1", logger, debug1,
            false, false);
    CommonUtils.writeOutput("", prefix, "-debug1", logger, debug1, false, false);

    StringBuffer sb = new StringBuffer();
    try {
        Format formatter;
        Date date = new Date();
        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String dt = formatter.format(date);

        String VCS_WORKSPACE_DIR = CommonUtils.extractVariable("",
                CommonUtils.getFileOrSystemPropertyValue(studioPropertyName, "VCS_WORKSPACE_DIR"),
                "studio.properties", true);
        File absFile = new File(VCS_WORKSPACE_DIR);
        String VCS_WORKSPACE_DIR_ABS = CommonUtils.setCanonicalPath(absFile.getCanonicalPath());

        String VCS_PROJECT_ROOT = CommonUtils.extractVariable("",
                CommonUtils.getFileOrSystemPropertyValue(studioPropertyName, "VCS_PROJECT_ROOT"),
                "studio.properties", true);

        // Set the workspace path to the workspace override
        String vcsWorkspacePath = vcsWorkspacePathOverride;

        // If the vcs workspace path override is null then derive the path from the studio.properties.
        if (vcsWorkspacePath == null || vcsWorkspacePath.length() == 0) {
            vcsWorkspacePath = (VCS_WORKSPACE_DIR_ABS + "/" + VCS_PROJECT_ROOT);
            System.out.println("VCS_WORKSPACE_DIR=" + VCS_WORKSPACE_DIR_ABS);
            System.out.println("VCS_PROJECT_ROOT=" + VCS_PROJECT_ROOT);
            System.out.println("vcsWorkspacePath=[" + vcsWorkspacePath + "]");
        }

        CommonUtils.writeOutput("--- INTERNAL WORKING PARAMETERS ----", prefix, "-debug1", logger, debug1,
                false, false);
        CommonUtils.writeOutput("", prefix, "-debug1", logger, debug1, false, false);
        CommonUtils.writeOutput("VCS_WORKSPACE_DIR=" + VCS_WORKSPACE_DIR_ABS, prefix, "-debug1", logger, debug1,
                false, false);
        CommonUtils.writeOutput("VCS_PROJECT_ROOT=" + VCS_PROJECT_ROOT, prefix, "-debug1", logger, debug1,
                false, false);
        CommonUtils.writeOutput("pre-mod: vcsWorkspacePath=[" + vcsWorkspacePath + "]", prefix, "-debug1",
                logger, debug1, false, false);

        // Change all backslash to forward slashes to normalize the path
        vcsWorkspacePath = vcsWorkspacePath.replaceAll(Matcher.quoteReplacement("\\\\"),
                Matcher.quoteReplacement("/"));
        //         System.out.println("vcsWorkspacePath="+vcsWorkspacePath);

        // Change all backslash to forward slashes to normalize the path
        vcsWorkspacePath = vcsWorkspacePath.replaceAll(Matcher.quoteReplacement("\\"),
                Matcher.quoteReplacement("/"));
        //         System.out.println("vcsWorkspacePath="+vcsWorkspacePath);

        // Create a double backslash for paths
        vcsWorkspacePath = vcsWorkspacePath.replaceAll(Matcher.quoteReplacement("/"),
                Matcher.quoteReplacement("\\\\"));
        //         System.out.println("vcsWorkspacePath="+vcsWorkspacePath);

        // Add \ in front of the C: so it will be C\:
        if (!vcsWorkspacePath.contains("\\:"))
            vcsWorkspacePath = vcsWorkspacePath.replaceAll(Matcher.quoteReplacement(":"),
                    Matcher.quoteReplacement("\\:"));
        //         System.out.println("vcsWorkspacePath="+vcsWorkspacePath);

        // Change C\\: to C\:
        if (vcsWorkspacePath.contains("\\\\:"))
            vcsWorkspacePath = vcsWorkspacePath.replaceAll(Matcher.quoteReplacement("\\\\:"),
                    Matcher.quoteReplacement("\\:"));
        //         System.out.println("vcsWorkspacePath="+vcsWorkspacePath);

        //         System.out.println("vcsWorkspacePath=["+vcsWorkspacePath+"]");
        CommonUtils.writeOutput("post-mod: vcsWorkspacePath=[" + vcsWorkspacePath + "]", prefix, "-debug1",
                logger, debug1, false, false);

        // If the vcs script bin folder name override is null then derive the path from the default /bin location.
        String vcsScriptFolder = (PDToolHomeDir + "/bin");
        if (vcsScriptBinFolderOverride != null && vcsScriptBinFolderOverride.length() > 0)
            vcsScriptFolder = (PDToolHomeDir + "/" + vcsScriptBinFolderOverride);

        CommonUtils.writeOutput("pre-mod: vcsScriptFolder=[" + vcsScriptFolder + "]", prefix, "-debug1", logger,
                debug1, false, false);
        //         System.out.println("vcsScriptFolder="+vcsScriptFolder);

        // Change all backslash to forward slashes to normalize the path
        vcsScriptFolder = vcsScriptFolder.replaceAll(Matcher.quoteReplacement("\\\\"),
                Matcher.quoteReplacement("/"));
        //         System.out.println("vcsScriptFolder="+vcsScriptFolder);

        // Change all backslash to forward slashes to normalize the path
        vcsScriptFolder = vcsScriptFolder.replaceAll(Matcher.quoteReplacement("\\"),
                Matcher.quoteReplacement("/"));
        //         System.out.println("vcsScriptFolder="+vcsScriptFolder);

        // Create a double backslash for paths
        vcsScriptFolder = vcsScriptFolder.replaceAll(Matcher.quoteReplacement("/"),
                Matcher.quoteReplacement("\\\\"));

        // Add \ in front of the C: so it will be C\:
        if (!vcsScriptFolder.contains("\\:"))
            vcsScriptFolder = vcsScriptFolder.replaceAll(Matcher.quoteReplacement(":"),
                    Matcher.quoteReplacement("\\:"));
        //         System.out.println("vcsScriptFolder="+vcsScriptFolder);

        // Change C\\: to C\:
        if (vcsScriptFolder.contains("\\\\:"))
            vcsScriptFolder = vcsScriptFolder.replaceAll(Matcher.quoteReplacement("\\\\:"),
                    Matcher.quoteReplacement("\\:"));
        //         System.out.println("vcsScriptFolder="+vcsScriptFolder);

        //         System.out.println("vcsScriptFolder=["+vcsScriptFolder+"]");
        CommonUtils.writeOutput("post-mod: vcsScriptFolder=[" + vcsScriptFolder + "]", prefix, "-debug1",
                logger, debug1, false, false);

        sb.append("# Generated by ExecutePDToolStudio.bat\n");
        sb.append("# " + dt + "\n");
        sb.append("vcsIncludeResourceSecurity=" + vcsIncludeResourceSecurity + "\n");
        sb.append("vcsScriptFolder=" + vcsScriptFolder + "\n");
        sb.append("vcsWorkspacePath=" + vcsWorkspacePath + "\n");
        sb.append("enableVCS=true" + "\n");
    } catch (Exception e) {
        throw new ValidationException(e.getMessage(), e);
    }

    try {
        Writer out = new OutputStreamWriter(new FileOutputStream(propertyFilePath));
        out.write(sb.toString());
        out.flush();

        String fileContents = CommonUtils.getFileAsString(propertyFilePath);
        System.out.println("");
        System.out.println("");
        System.out.println(
                "-----------------------------------------------------------------------------------------------------");
        System.out.println("Property File Contents For [" + propertyFilePath + "]");
        System.out.println(
                "-----------------------------------------------------------------------------------------------------");
        System.out.println(fileContents);
        System.out.println("");
        CommonUtils.writeOutput("Property File Contents For [" + propertyFilePath + "]", prefix, "-debug1",
                logger, debug1, false, false);
        CommonUtils.writeOutput(fileContents, prefix, "-debug1", logger, debug1, false, false);

    } catch (FileNotFoundException e) {
        logger.error("Could not wirte to property file " + propertyFilePath, e);
        throw new ValidationException(e.getMessage(), e);
    } catch (IOException e) {
        logger.error("Could not wirte to property file " + propertyFilePath, e);
        throw new ValidationException(e.getMessage(), e);
    }
}

From source file:com.github.mavogel.ilias.printer.VelocityOutputPrinter.java

/**
 * Prints the header, content and output to the given print stream with the default template from the classpath.
 *
 * @param outputType the desired output type. @see {@link OutputType}
 * @param contextMap the context for velocity
 * @throws Exception in case of a error, so the caller can handle it
 *//*  ww  w  .  ja  v  a2s .  c  o m*/
private static void printWithDefaultTemplate(final OutputType outputType, final Map<String, Object> contextMap)
        throws Exception {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.init();

    Writer writer = null;
    final String templateName = outputType.getDefaultTemplateLocation();
    try {
        VelocityContext context = new VelocityContext();
        contextMap.forEach((k, v) -> context.put(k, v));
        Template template = ve.getTemplate(templateName, "UTF-8");
        writer = new BufferedWriter(createFileWriter(outputType, templateName));

        template.merge(context, writer);
        writer.flush();
    } catch (ResourceNotFoundException rnfe) {
        LOG.error("Couldn't find the template with name '" + templateName + "'");
        throw new Exception(rnfe.getMessage());
    } catch (ParseErrorException pee) {
        LOG.error("Syntax error: problem parsing the template ' " + templateName + "': " + pee.getMessage());
        throw new Exception(pee.getMessage());
    } catch (MethodInvocationException mie) {
        LOG.error(
                "An invoked method on the template '" + templateName + "' threw an error: " + mie.getMessage());
        throw new Exception(mie.getMessage());
    } catch (Exception e) {
        LOG.error("Error: " + e.getMessage());
        LOG.error("Cause: " + e.getCause());
        Arrays.stream(e.getStackTrace()).forEach(LOG::error);
        throw e;
    } finally {
        if (writer != null)
            writer.close();
    }
}

From source file:com.xqdev.jam.MLJAM.java

private static void sendStringResponse(HttpServletResponse res, String s) throws IOException {
    res.setContentType("text/plain; charset=UTF-8");
    Writer w = res.getWriter();
    w.write(s);/* ww w.  jav a  2s.  c o m*/
    w.flush();
}

From source file:jp.crudefox.mymon.picturetool.api.Caker.java

private static void writeUrlEncoded(OutputStream out, Charset charset, List<Pair<String, Object>> params)
        throws IOException {

    Writer writer = new BufferedWriter(new OutputStreamWriter(out, charset));
    boolean first = true;
    for (Pair<String, Object> nameValuePair : params) {
        String name = nameValuePair.first;
        Object value = nameValuePair.second;
        if (value != null) {
            appendParam(writer, name, value, first);
            first = false;//ww w .  jav a 2s .c om
        }
    }
    writer.flush();
}

From source file:com.netxforge.oss2.core.xml.CastorUtils.java

/**
 * Marshal a Castor XML configuration file.
 *
 * @param obj the object representing the objected to be marshalled to XML
 * @throws org.springframework.dao.DataAccessException if the underlying Castor
 *      Marshaller.marshal() call throws a MarshalException or
 *      ValidationException.  The underlying exception will be translated
 *      using MarshallingExceptionTranslator.
 * @param resource a {@link org.springframework.core.io.Resource} object.
 */// w w w.  ja va 2  s  .  c o m
public static void marshalWithTranslatedExceptionsViaString(Object obj, Resource resource)
        throws DataAccessException {
    Writer fileWriter = null;
    try {
        StringWriter writer = new StringWriter();
        marshal(obj, writer);

        fileWriter = new OutputStreamWriter(new FileOutputStream(resource.getFile()), "UTF-8");
        fileWriter.write(writer.toString());
        fileWriter.flush();

    } catch (IOException e) {
        throw CASTOR_EXCEPTION_TRANSLATOR.translate("marshalling XML file", e);
    } catch (MarshalException e) {
        throw CASTOR_EXCEPTION_TRANSLATOR.translate("marshalling XML file", e);
    } catch (ValidationException e) {
        throw CASTOR_EXCEPTION_TRANSLATOR.translate("marshalling XML file", e);
    } finally {
        IOUtils.closeQuietly(fileWriter);
    }
}

From source file:com.xqdev.jam.MLJAM.java

private static void sendClientProblemResponse(HttpServletResponse res, String s) throws IOException {
    // Commenting out the status code because we want the client to eval the error() call
    //res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    if (s != null && s.length() > 4096) { // Cap super long errors
        s = s.substring(0, 2048) + " ...[trimmed]... " + s.substring(s.length() - 2048);
    }/*from  ww  w.  ja  v a  2 s  .  co m*/
    res.setContentType("x-marklogic/xquery; charset=UTF-8");
    Writer writer = res.getWriter();
    writer.write("error('" + escapeSingleQuotes(s) + "')");
    writer.flush();
}