Example usage for java.io FileOutputStream flush

List of usage examples for java.io FileOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:Gen.java

public static void genWeb() throws Exception {

    String GEN_WEBINF = GEN_ROOT + FILE_SEPARATOR + "war" + FILE_SEPARATOR + "WEB-INF";

    String WAR_NAME = System.getProperty("warname") != null && !System.getProperty("warname").equals("")
            ? System.getProperty("warname")
            : MAPPING_JAR_NAME.substring(0, MAPPING_JAR_NAME.length() - "jar".length()) + "war";
    if (!WAR_NAME.endsWith(".war"))
        WAR_NAME += ".war";

    String PROPS_EMBED = System.getProperty("propsembed") != null
            && !System.getProperty("propsembed").equals("") ? System.getProperty("propsembed") : null;

    deleteDir(GEN_ROOT + FILE_SEPARATOR + "war");

    regenerateDir(GEN_WEBINF + FILE_SEPARATOR + "classes");
    regenerateDir(GEN_WEBINF + FILE_SEPARATOR + "lib");

    Vector<String> warJars = new Vector<String>();
    warJars.add(GEN_ROOT_LIB + FILE_SEPARATOR + MAPPING_JAR_NAME);

    InputStream inputStreamCore = Gen.class.getResourceAsStream("/biocep-core-tomcat.jar");
    if (inputStreamCore != null) {
        try {//from   w w w  . ja  v a  2 s  . c  o m
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(
                    GEN_WEBINF + FILE_SEPARATOR + "lib" + "/biocep-core.jar");
            int count = 0;
            while ((count = inputStreamCore.read(data, 0, BUFFER_SIZE)) != -1) {
                fos.write(data, 0, count);
            }
            fos.flush();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {

        warJars.add("RJB.jar");

        warJars.add("lib/desktop/JRI.jar");

        FilenameFilter jarsFilter = new FilenameFilter() {
            public boolean accept(File arg0, String arg1) {
                return arg1.endsWith(".jar");
            }
        };

        {
            String[] derby_jdbc_jars = new File("lib/jdbc").list(jarsFilter);
            for (int i = 0; i < derby_jdbc_jars.length; ++i) {
                warJars.add("lib/jdbc" + FILE_SEPARATOR + derby_jdbc_jars[i]);
            }
        }

        {
            String[] pool_jars = new File("lib/pool").list(jarsFilter);
            for (int i = 0; i < pool_jars.length; ++i) {
                warJars.add("lib/pool" + FILE_SEPARATOR + pool_jars[i]);
            }
        }

        {
            String[] httpclient_jars = new File("lib/j2ee").list(jarsFilter);
            for (int i = 0; i < httpclient_jars.length; ++i) {
                warJars.add("lib/j2ee" + FILE_SEPARATOR + httpclient_jars[i]);
            }
        }
    }

    log.info(warJars);
    for (int i = 0; i < warJars.size(); ++i) {
        Copy copyTask = new Copy();
        copyTask.setProject(_project);
        copyTask.setTaskName("copy to war");
        copyTask.setTodir(new File(GEN_WEBINF + FILE_SEPARATOR + "lib"));
        copyTask.setFile(new File(warJars.elementAt(i)));
        copyTask.init();
        copyTask.execute();
    }

    unzip(Gen.class.getResourceAsStream("/jaxws.zip"), GEN_WEBINF + FILE_SEPARATOR + "lib",
            new EqualNameFilter("activation.jar", "jaxb-api.jar", "jaxb-impl.jar", "jaxb-xjc.jar",
                    "jaxws-api.jar", "jaxws-libs.jar", "jaxws-rt.jar", "jaxws-tools.jar", "jsr173_api.jar",
                    "jsr181-api.jar", "jsr250-api.jar", "saaj-api.jar", "saaj-impl.jar", "sjsxp.jar",
                    "FastInfoset.jar", "http.jar", "mysql-connector-java-5.1.0-bin.jar", "ojdbc-14.jar"),
            BUFFER_SIZE, false, "Unzipping psTools..", 17);

    PrintWriter pw_web_xml = new PrintWriter(GEN_WEBINF + FILE_SEPARATOR + "web.xml");
    pw_web_xml.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    pw_web_xml.println(
            "<web-app version=\"2.4\" xmlns=\"http://java.sun.com/xml/ns/j2ee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\">");
    pw_web_xml.println(
            "<listener><listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class></listener>");

    for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
        String shortClassName = className.substring(className.lastIndexOf('.') + 1);
        pw_web_xml.println("<servlet><servlet-name>" + shortClassName
                + "_servlet</servlet-name><servlet-class>org.kchine.r.server.http.frontend.InterceptorServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>");
    }

    pw_web_xml.println("<servlet><servlet-name>" + "WSServlet"
            + "</servlet-name><servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>");

    pw_web_xml.println("<servlet><servlet-name>" + "MappingClassServlet"
            + "</servlet-name><servlet-class>org.kchine.r.server.http.frontend.MappingClassServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>");

    for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
        String shortClassName = className.substring(className.lastIndexOf('.') + 1);
        pw_web_xml.println(
                "<servlet-mapping><servlet-name>" + shortClassName + "_servlet</servlet-name><url-pattern>/"
                        + shortClassName + "</url-pattern></servlet-mapping>");
    }

    pw_web_xml.println("<servlet-mapping><servlet-name>" + "MappingClassServlet"
            + "</servlet-name><url-pattern>" + "/mapping/classes/*" + "</url-pattern></servlet-mapping>");

    pw_web_xml.println("<session-config><session-timeout>30</session-timeout></session-config>");
    pw_web_xml.println("</web-app>");
    pw_web_xml.flush();
    pw_web_xml.close();

    PrintWriter pw_sun_jaxws_xml = new PrintWriter(GEN_WEBINF + FILE_SEPARATOR + "sun-jaxws.xml");
    pw_sun_jaxws_xml.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    pw_sun_jaxws_xml.println("<endpoints xmlns='http://java.sun.com/xml/ns/jax-ws/ri/runtime' version='2.0'>");

    for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
        String shortClassName = className.substring(className.lastIndexOf('.') + 1);
        pw_sun_jaxws_xml.println("   <endpoint    name='name_" + shortClassName + "'   implementation='"
                + className + "Web" + "' url-pattern='/" + shortClassName + "'/>");
    }

    pw_sun_jaxws_xml.println("</endpoints>");
    pw_sun_jaxws_xml.flush();
    pw_sun_jaxws_xml.close();

    if (PROPS_EMBED != null) {
        InputStream is = new FileInputStream(PROPS_EMBED);
        byte[] buffer = new byte[is.available()];
        is.read(buffer);
        RandomAccessFile raf = new RandomAccessFile(
                GEN_WEBINF + FILE_SEPARATOR + "classes" + FILE_SEPARATOR + "globals.properties", "rw");
        raf.setLength(0);
        raf.write(buffer);
        raf.close();
    }

    War warTask = new War();
    warTask.setProject(_project);
    warTask.setTaskName("war");
    warTask.setBasedir(new File(GEN_ROOT + FILE_SEPARATOR + "war"));
    warTask.setDestFile(new File(GEN_ROOT + FILE_SEPARATOR + WAR_NAME));
    warTask.setIncludes("**/*");
    warTask.init();
    warTask.execute();

}

From source file:gate.DocumentExporter.java

/**
 * Equivalent to {@link #export(Document,OutputStream,FeatureMap)} using a
 * FileOutputStream instance constructed from the File param.
 *//*  ww  w  .  j a v a 2 s. co  m*/
public void export(Document doc, File file, FeatureMap options) throws IOException {
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(file);
        export(doc, new FileOutputStream(file), options);
        out.flush();
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:gumga.framework.application.report.ReportTest.java

@Test
public void testGenerateAndExportReportToPDF() throws Exception {
    InputStream is = getInputStreamReportFile();
    String outputFile = System.getProperty("java.io.tmpdir") + "/reportOutput.pdf";
    FileOutputStream fos = new FileOutputStream(new File(outputFile));
    try {//from  www  .java 2 s .c o  m
        reportService.exportReport(is, fos, createContactList(), null, ReportType.PDF);
    } finally {
        fos.flush();
        fos.close();
    }
    assertTrue(new File(outputFile).exists());
}

From source file:com.meltmedia.cadmium.core.config.impl.PropertiesWriterImpl.java

@Override
public void persistProperties(Properties properties, File propsFile, String message, Logger log) {

    if (propsFile.canWrite() || !propsFile.exists()) {

        FileOutputStream out = null;

        try {/*from  w w  w  . j ava2  s.  co m*/

            ensureDirExists(propsFile.getParent());
            out = new FileOutputStream(propsFile);
            properties.store(out, message);
            out.flush();
        } catch (Exception e) {

            log.warn("Failed to persist vault properties file.", e);
        } finally {
            IOUtils.closeQuietly(out);
        }

    }

}

From source file:com.cloud.agent.dao.impl.PropertiesStorage.java

@Override
public synchronized void persist(String key, String value) {
    _properties.setProperty(key, value);
    FileOutputStream output = null;
    try {/*from  w ww .  j a v  a2 s  .  c o m*/
        output = new FileOutputStream(_file);
        _properties.store(output, _name);
        output.flush();
        output.close();
    } catch (IOException e) {
        s_logger.error("Uh-oh: ", e);
    } finally {
        IOUtils.closeQuietly(output);
    }
}

From source file:com.tri_voltage.md.io.YoutubeVideoParser.java

private static void downloadWithHttpClient(String userAgent, String downloadUrl, File outputfile)
        throws Throwable {
    HttpGet httpget2 = new HttpGet(downloadUrl);
    if (userAgent != null && userAgent.length() > 0) {
        httpget2.setHeader("User-Agent", userAgent);
    }//from  w ww  .j  av  a  2s  .c o m

    log.finer("Executing " + httpget2.getURI());
    HttpClient httpclient2 = HttpClientBuilder.create().build();
    HttpResponse response2 = httpclient2.execute(httpget2);
    HttpEntity entity2 = response2.getEntity();
    if (entity2 != null && response2.getStatusLine().getStatusCode() == 200) {
        double length = entity2.getContentLength();
        if (length <= 0) {
            // Unexpected, but do not divide by zero
            length = 1;
        }
        InputStream instream2 = entity2.getContent();
        System.out.println("Writing " + commaFormatNoPrecision.format(length) + " bytes to " + outputfile);
        if (outputfile.exists()) {
            outputfile.delete();
        }
        FileOutputStream outstream = new FileOutputStream(outputfile);
        try {
            byte[] buffer = new byte[BUFFER_SIZE];
            double total = 0;
            int count = -1;
            int progress = 10;
            long start = System.currentTimeMillis();
            while ((count = instream2.read(buffer)) != -1) {
                total += count;
                int p = (int) ((total / length) * ONE_HUNDRED);
                if (p >= progress) {
                    long now = System.currentTimeMillis();
                    double s = (now - start) / 1000;
                    int kbpers = (int) ((total / KB) / s);
                    System.out.println(progress + "% (" + kbpers + "KB/s)");
                    progress += 10;
                }
                outstream.write(buffer, 0, count);
            }
            outstream.flush();
        } finally {
            outstream.close();
        }
        System.out.println("Done");
    }
}

From source file:cn.leancloud.diamond.server.service.AdminService.java

private boolean saveToDisk() {
    FileOutputStream out = null;
    try {/*  www . ja va 2s . c  o m*/
        out = new FileOutputStream(url.getPath());
        this.properties.store(out, "add user");
        out.flush();
        return true;
    } catch (IOException e) {
        log.error("?user.properties", e);
        return false;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                log.error("user.properties", e);
            }
        }
    }
}

From source file:com.starit.diamond.server.service.UserService.java

private boolean saveToDisk() {
    FileOutputStream out = null;
    try {//from   w  w w  .j a  va 2s .c  om
        out = new FileOutputStream(url.getPath());
        this.properties.store(out, "add user");
        out.flush();
        return true;
    } catch (IOException e) {
        LOGGER.error("?user.properties", e);
        return false;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                LOGGER.error("user.properties", e);
            }
        }
    }
}

From source file:com.taobao.diamond.server.service.AdminService.java

private boolean saveToDisk() {
    FileOutputStream out = null;
    try {/*w ww  .j  a v  a 2  s.  co m*/
        out = new FileOutputStream(url.getPath());
        this.properties.store(out, "add user");
        out.flush();
        return true;
    } catch (IOException e) {
        log.error("user.properties", e);
        return false;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                log.error("user.properties", e);
            }
        }
    }
}

From source file:plugins.marauders.MaraudersPOSTServlet.java

@Override
public HttpResponse handleRequest(HttpRequest request) {
    String body = new String(request.getBody());
    ObjectMapper mapper = new ObjectMapper();
    TypeReference<HashMap<String, Object>> typeReference = new TypeReference<HashMap<String, Object>>() {
    };//from w  w w.  ja  v  a 2  s  .  c om
    try {
        HashMap<String, Object> map = mapper.readValue(body, typeReference);
        String nameObj = (String) map.get("name");
        String passphraseObj = (String) map.get("passphrase");

        String locationObj = (String) map.get("location");
        Data d = MaraudersInteractor.getData();
        boolean okPassphrase = passphraseObj.equals(d.passphrase);
        if (okPassphrase) {
            boolean b = MaraudersInteractor.updateStudentLocation(nameObj, locationObj);
            if (b) {
                Student s = MaraudersInteractor.getStudent(nameObj);
                s.setLocation(locationObj);
                try {
                    File f = File.createTempFile("temp", ".txt");

                    FileOutputStream fos = new FileOutputStream(f);
                    fos.write((s.toString()).getBytes());
                    fos.flush();
                    fos.close();
                    Thread.sleep(100);
                    HttpResponse res = HttpResponseFactory.create200OK(f, Protocol.CLOSE);

                    return res;
                } catch (Exception e) {
                    e.printStackTrace();
                    return HttpResponseFactory.create400BadRequest(Protocol.CLOSE);
                }
            }
        } else {
            Random rand = new Random();
            int id = rand.nextInt(d.maxInsultID + 1);

            try {
                Insult i = MaraudersInteractor.getInsult(id + "");
                File f = File.createTempFile("temp", ".txt");

                FileOutputStream fos = new FileOutputStream(f);
                fos.write((i.toString()).getBytes());
                fos.flush();
                fos.close();

                HttpResponse res = HttpResponseFactory.create394Insult(f, Protocol.CLOSE);
                //f.delete();
                return res;
            } catch (Exception e) {
                e.printStackTrace();
                return HttpResponseFactory.create400BadRequest(Protocol.CLOSE);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return HttpResponseFactory.create400BadRequest(Protocol.CLOSE);

}