Example usage for java.io PrintWriter flush

List of usage examples for java.io PrintWriter flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flushes the stream.

Usage

From source file:TextFileHandler.java

/**
 * Save content to a .gz file/*w  w w . java 2 s .com*/
 * @param fileName e.g. foo.txt.gz
 * @param content
 */
public void saveGZipFile(String fileName, String content) {
    try {
        GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(fileName));
        PrintWriter pw = new PrintWriter(out);
        pw.write(content);
        pw.flush();
        pw.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.cloudbees.hudson.plugins.folder.computed.EventOutputStreamsTest.java

public void test(final boolean aFlush, final boolean bFlush) throws Exception {
    final File file = work.newFile();
    final EventOutputStreams instance = new EventOutputStreams(new EventOutputStreams.OutputFile() {
        @NonNull/*  w ww.j av a 2 s.  co m*/
        @Override
        public File get() {
            return file;
        }
    }, 250, TimeUnit.MILLISECONDS, 8192, false, Long.MAX_VALUE, 0);
    Thread t1 = new Thread() {
        public void run() {
            OutputStream os = instance.get();
            try {
                PrintWriter pw = new PrintWriter(os, aFlush);
                for (int i = 0; i < 10000; i += 1) {
                    pw.println(String.format("%1$05dA", i));
                }
                pw.flush();
            } catch (Throwable e) {
                e.printStackTrace(System.err);
            } finally {
                IOUtils.closeQuietly(os);
            }
        }
    };
    Thread t2 = new Thread() {
        public void run() {
            OutputStream os = instance.get();
            try {
                PrintWriter pw = new PrintWriter(os, bFlush);
                for (int i = 0; i < 10000; i += 1) {
                    pw.println(String.format("%1$05dB", i));
                }
                pw.flush();
            } catch (Throwable e) {
                e.printStackTrace(System.err);
            } finally {
                IOUtils.closeQuietly(os);
            }
        }
    };
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    List<String> as = new ArrayList<String>();
    List<String> bs = new ArrayList<String>();
    for (String line : FileUtils.readLines(file)) {
        assertThat("Line does not have both thread output: '" + StringEscapeUtils.escapeJava(line) + "'",
                line.matches("^\\d+[AB](\\d+[AB])+$"), is(false));
        assertThat("Line does not contain a null character: '" + StringEscapeUtils.escapeJava(line) + "'",
                line.indexOf(0), is(-1));
        if (line.endsWith("A")) {
            as.add(line);
        } else if (line.endsWith("B")) {
            bs.add(line);
        } else {
            fail("unexpected line: '" + StringEscapeUtils.escapeJava(line) + "'");
        }
    }
    List<String> sorted = new ArrayList<String>(as);
    Collections.sort(sorted);
    assertThat(as, is(sorted));
    sorted = new ArrayList<String>(bs);
    Collections.sort(sorted);
    assertThat(bs, is(sorted));
}

From source file:com.github.dmyersturnbull.transformations.CommandLineHelper.java

public void printHelp(@Nonnull PrintWriter pw) {
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp(pw, sf_helpWidth, m_class.map(Class::getSimpleName).orElse("<unknown class>"),
            m_helpHeader, m_options, 0, 0, m_helpFooter, true);
    pw.flush();
}

From source file:net.sf.j2ep.responsehandlers.TraceResponseHandler.java

/**
 * Will either respond with data from the underlying server
 * or the proxy's own data.//from   w  ww. j  a v  a  2 s  .  c om
 * @see net.sf.j2ep.model.ResponseHandler#process(javax.servlet.http.HttpServletResponse)
 */
public void process(HttpServletResponse response) throws IOException {

    if (proxyTargeted) {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("content-type", "message/http");
        response.setHeader("Connection", "close");

        String path = method.getPath();
        String protocol = method.getParams().getVersion().toString();
        PrintWriter writer = response.getWriter();
        writer.println("TRACE " + path + " " + protocol);
        Header[] headers = method.getRequestHeaders();
        for (int i = 0; i < headers.length; i++) {
            writer.print(headers[i]);
        }
        writer.flush();
        writer.close();

    } else {
        setHeaders(response);
        response.setStatus(getStatusCode());
        sendStreamToClient(response);
    }
}

From source file:ai.baby.servlets.GenericFileGrabber.java

private PrintWriter flush(final PrintWriter out) {
    out.flush();
    return out;
}

From source file:com.bmwcarit.barefoot.tracker.TrackerServerTest.java

public void sendSample(InetAddress host, int port, JSONObject sample) throws InterruptedException, IOException {
    int trials = 120;
    int timeout = 500;
    Socket client = null;/*from   w w w. ja  v a  2s  . co  m*/

    while (client == null || !client.isConnected()) {
        try {
            client = new Socket(host, port);
        } catch (IOException e) {
            Thread.sleep(timeout);

            if (trials == 0) {
                logger.error(e.getMessage());
                client.close();
                throw new IOException();
            } else {
                trials -= 1;
            }
        }
    }

    PrintWriter writer = new PrintWriter(client.getOutputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    writer.println(sample.toString());
    writer.flush();

    String code = reader.readLine();
    assertEquals("SUCCESS", code);
}

From source file:RegisterTest.java

/**
 * Test of processRequest method, of class Register.
 * @throws java.lang.Exception/*  ww  w . ja v  a 2  s.c om*/
 */
@Test
public void testProcessRequest() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);

    when(request.getParameter("uid")).thenReturn("me");
    when(request.getParameter("pass")).thenReturn("secret");
    PrintWriter writer = new PrintWriter("testregister.txt");
    when(response.getWriter()).thenReturn(writer);
    Register instance = new Register();
    instance.doPost(request, response);

    verify(request, atLeast(1)).getParameter("name"); // only if you want to verify username was called...
    writer.flush(); // it may not have been flushed yet...
    assertTrue(FileUtils.readFileToString(new File("testregister.txt"), "UTF-8")
            .contains("You are sucessfully registered"));
}

From source file:com.nginious.http.serialize.JsonSerializerTestCase.java

public void testEmptyJsonSerializer() throws Exception {
    SerializableBean bean = new SerializableBean();
    ApplicationClassLoader classLoader = new ApplicationClassLoader(
            Thread.currentThread().getContextClassLoader());
    SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader);
    Serializer<SerializableBean> serializer = serializerFactory.createSerializer(SerializableBean.class,
            "application/json");
    assertEquals("application/json", serializer.getMimeType());

    StringWriter strWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(strWriter);
    serializer.serialize(writer, bean);//  www  .  java 2s. c o m
    writer.flush();
    JSONObject json = new JSONObject(strWriter.toString());
    assertNotNull(json);
    assertTrue(json.has("serializableBean"));
    json = json.getJSONObject("serializableBean");

    assertEquals(false, json.getBoolean("booleanValue"));
    assertEquals(0.0d, json.getDouble("doubleValue"));
    assertEquals(0.0f, (float) json.getDouble("floatValue"));
    assertEquals(0, json.getInt("intValue"));
    assertEquals(0L, json.getLong("longValue"));
    assertEquals(0, (short) json.getInt("shortValue"));
    assertFalse(json.has("stringValue"));
    assertFalse(json.has("dateValue"));
    assertFalse(json.has("calendarValue"));
    assertFalse(json.has("objectValue"));
}

From source file:imageviewer.util.PasswordGenerator.java

private void write(File f) throws IOException {

    PrintWriter pw = new PrintWriter(f);
    for (String userName : userList) {
        pw.println(userName + ":" + new String(userTable.get(userName)));
        pw.flush();
    }/*from   www . j av  a 2s  .com*/
    pw.close();
}

From source file:com.jjtree.servelet.Login.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w  w  w .  j a  v a  2  s. c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    JSONObject jsonObject = JConverter.convert(request);
    if (jsonObject == null) {
        return;
    }

    String account = null;
    String password = null;
    try {
        account = jsonObject.getString("account");
        password = jsonObject.getString("password");

        if (account == null || password == null) {
            return;
        }
    } catch (JSONException ex) {
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        // Register JDBC driver
        Class.forName(JConstant.JDBC_DRIVER);

        // Open a connection
        conn = DriverManager.getConnection(JConstant.DB_URL, JConstant.USER, JConstant.PASSWORD);

        // Execute SQL query
        stmt = conn.createStatement();
        String sql = null;

        boolean isPhone = JString.isPhoneNumber(account);
        if (isPhone) {
            sql = "SELECT * FROM JUser WHERE mobile = '" + account + "'";
        }

        boolean isEmail = JString.isEmail(account);
        if (isEmail) {
            sql = "SELECT * FROM JUser WHERE email = '" + account + "'";
        }

        ResultSet rs = stmt.executeQuery(sql);

        // Extract data from result set
        while (rs.next()) {
            //Retrieve by column name
            int accountID = rs.getInt("userID");

            String pass = rs.getString("password");

            if (password != null) {
                if (password.equals(pass)) {
                    String accountUrl = "/accounts/" + accountID;
                    JSONObject accountObject = JServeletManager.fetchFrom(request, accountUrl);

                    PrintWriter writer = response.getWriter();
                    writer.print(accountObject);
                    writer.flush();
                }
            }
        }

        // Clean-up environment
        rs.close();
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        try {
            //Handle errors for JDBC
            JResponse.sendErrorMessage(1, "login failed!", response);
        } catch (JSONException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        se.printStackTrace();
    } catch (Exception e) {
        try {
            //Handle errors for JDBC
            JResponse.sendErrorMessage(1, "login failed!", response);
        } catch (JSONException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        //Handle errors for Class.forName
        e.printStackTrace();
    } finally {
        //finally block used to close resources
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException se2) {
        } // nothing we can do
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            se.printStackTrace();
        } //end finally try
    } //end try
}