Example usage for java.io PrintStream flush

List of usage examples for java.io PrintStream flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flushes the stream.

Usage

From source file:edu.wisc.jmeter.MonitorListener.java

/**
 * Saves data from the last response to a file
 *///from   w ww.j  a  v a 2s.com
private void saveResponseToFile(SampleResult sampleResult, Date now, String userId, String hostName,
        String errorMessages, int errorCount, int messageCount) {
    final String formatedDate;
    synchronized (RESPONSE_FILE_DATE_FORMAT) {
        formatedDate = RESPONSE_FILE_DATE_FORMAT.format(now);
    }
    final File responseFile = new File(logLocation, formatedDate + "." + hostName + ".response");

    PrintStream ps = null;
    try {
        ps = new PrintStream(responseFile);

        final String respHeaders = sampleResult.getResponseHeaders();
        final String respData = sampleResult.getResponseDataAsString();

        ps.println("Sampler Label: " + sampleResult.getSampleLabel());
        ps.println("Portal User: " + userId);
        ps.println("Consecutive Error Count: " + errorCount);
        ps.println("Sent Message Count: " + messageCount);
        ps.println("Error Messages: " + errorMessages);
        ps.println("--------------------------------------------------------------------------------");
        ps.print(respHeaders);
        ps.println("--------------------------------------------------------------------------------");
        ps.print(respData);
        ps.flush();

        log("Saved response to: " + responseFile);
    } catch (FileNotFoundException fnfe) {
        log("Failed to save response headers and body to file", fnfe);
    } finally {
        IOUtils.closeQuietly(ps);
    }
}

From source file:org.signserver.client.cli.defaultimpl.KeyStoreOptions.java

public void parseCommandLine(CommandLine line, ConsolePasswordReader passwordReader, PrintStream out)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
    if (line.hasOption(KeyStoreOptions.TRUSTSTORE)) {
        truststoreFile = new File(line.getOptionValue(KeyStoreOptions.TRUSTSTORE, null));
    }/*from   w  ww  .ja v  a  2 s.c o  m*/
    if (line.hasOption(KeyStoreOptions.TRUSTSTOREPWD)) {
        truststorePassword = line.getOptionValue(KeyStoreOptions.TRUSTSTOREPWD, null);
    }
    if (line.hasOption(KeyStoreOptions.KEYSTORE)) {
        keystoreFile = new File(line.getOptionValue(KeyStoreOptions.KEYSTORE, null));
    }
    if (line.hasOption(KeyStoreOptions.KEYSTOREPWD)) {
        keystorePassword = line.getOptionValue(KeyStoreOptions.KEYSTOREPWD, null);
    }
    if (line.hasOption(KeyStoreOptions.KEYALIAS)) {
        keyAlias = line.getOptionValue(KeyStoreOptions.KEYALIAS, null);
    }
    if (passwordReader != null) {
        // Prompt for truststore password if not given
        if (truststoreFile != null && truststorePassword == null) {
            for (int i = 0; i < 3; i++) {
                out.print("Password for truststore: ");
                out.flush();
                truststorePassword = new String(passwordReader.readPassword());
                try {
                    KeyStore keystore = KeyStore.getInstance("JKS");
                    keystore.load(new FileInputStream(truststoreFile), truststorePassword.toCharArray());
                    break;
                } catch (IOException ex) {
                    if (ex.getCause() instanceof UnrecoverableKeyException) {
                        if (i >= 2) {
                            throw ex;
                        }
                        continue;
                    } else {
                        throw ex;
                    }
                }
            }
        }
        // Prompt for keystore password if not given
        if (keystoreFile != null && keystorePassword == null) {
            for (int i = 0; i < 3; i++) {
                out.print("Password for keystore: ");
                out.flush();
                keystorePassword = new String(passwordReader.readPassword());
                try {
                    KeyStore keystore = KeyStore.getInstance("JKS");
                    keystore.load(new FileInputStream(keystoreFile), keystorePassword.toCharArray());
                    break;
                } catch (IOException ex) {
                    if (ex.getCause() instanceof UnrecoverableKeyException) {
                        if (i >= 2) {
                            throw ex;
                        }
                        continue;
                    } else {
                        throw ex;
                    }
                }
            }
        }
    }
}

From source file:org.exjello.mail.Exchange2003Connection.java

private RequestEntity createMessageEntity(MimeMessage message) throws Exception {
    final File tempFile = File.createTempFile("exmail", null, null);
    tempFile.deleteOnExit();//from w  w  w.ja  v a 2  s.c om
    OutputStream output = new BufferedOutputStream(new FileOutputStream(tempFile));
    message.writeTo(output);
    if (session.getDebug()) {
        PrintStream log = session.getDebugOut();
        log.println("Message Content:");
        message.writeTo(log);
        log.println();
        log.flush();
    }
    output.flush();
    output.close();
    InputStream stream = new FileInputStream(tempFile) {
        public void close() throws IOException {
            try {
                super.close();
            } finally {
                try {
                    if (!tempFile.delete())
                        tempFile.deleteOnExit();
                } catch (Exception ignore) {
                }
            }
        }
    };
    return new InputStreamRequestEntity(stream, tempFile.length(), MESSAGE_CONTENT_TYPE);
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test(timeOut = 5000)
public void testConnectionClose() throws Exception {
    URL url = baseURI.resolve("/test/v1/connectionClose").toURL();

    // Fire http request using raw socket so that we can verify the connection get closed by the server
    // after the response.
    Socket socket = createRawSocket(url);
    try {/*from   w  ww  . j  a  v  a  2  s .  co  m*/
        PrintStream printer = new PrintStream(socket.getOutputStream(), false, "UTF-8");
        printer.printf("GET %s HTTP/1.1\r\n", url.getPath());
        printer.printf("Host: %s:%d\r\n", url.getHost(), url.getPort());
        printer.print("\r\n");
        printer.flush();

        // Just read everything from the response. Since the server will close the connection, the read loop should
        // end with an EOF. Otherwise there will be timeout of this test case
        String response = IOUtils.toString(new InputStreamReader(socket.getInputStream(), Charsets.UTF_8));
        assertTrue(response.startsWith("HTTP/1.1 200 OK"));
    } finally {
        socket.close();
    }
}

From source file:com.fluidops.iwb.deepzoom.CXMLServlet.java

/**
 * We handle different types of requests:
 * 1) queries: these produce results according to the CXML standard, making reference to a collection.xml file 
 * 2) collection.xml files that contains the images for the query results
 * 3) the jpg images themselves/*  w w  w .  j  a  va 2s  . c  o m*/
 */
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String requestURI = req.getRequestURI();

    initialize();

    // this is the request for the images
    if (requestURI.endsWith("jpg") && requestURI.contains("dzimages")) { // The format of such a request is as follows: /pivot/dzimages/09/1113490945_files/6/0_0.jpg

        String filestring = requestURI.substring(req.getRequestURI().lastIndexOf("dzimages"));
        String filename = filestring.substring(filestring.indexOf("/") + 1, filestring.indexOf("_"));
        String substring = requestURI.substring(req.getRequestURI().lastIndexOf("files"));
        int zoomLevel = Integer
                .parseInt(substring.substring(substring.indexOf("/") + 1, substring.lastIndexOf("/")));

        try {
            DeepZoomCollection.handleTileRequest(filename, zoomLevel, resp);
        } catch (Exception e) {
            logger.trace("Exception while loading images: " + e.getMessage(), e);
            // TODO: for now, problems when loading images are ignored, only the exception on the console is avoided
        }
        return;
    }

    // this is the request for the images
    if (requestURI.endsWith("jpg")) { // The format of such a request is as follows: /wikipedia/collection3_files/8/0_0.jpg
                                      // wikipedia identifies the name of the global collection (currently we assume there is only one dynamic collection)
                                      // collection3 identifies the query that has generated a query result, which is a subset of the global collection
                                      // The 8 is the zoom level (how deep we have zoomed in)
                                      // 0_0 identified the position of the tile (horizontal and vertical offset)

        int queryNumber = Integer
                .parseInt(requestURI.substring(requestURI.indexOf("collection") + 10, requestURI.indexOf("_")));
        String substring = requestURI.substring(req.getRequestURI().lastIndexOf("files"));
        int zoomLevel = Integer
                .parseInt(substring.substring(substring.indexOf("/") + 1, substring.lastIndexOf("/")));
        int x_Offset = Integer
                .parseInt(substring.substring(substring.lastIndexOf("/") + 1, substring.lastIndexOf("_")));
        int y_Offset = Integer
                .parseInt(substring.substring(substring.lastIndexOf("_") + 1, substring.lastIndexOf(".")));

        Vector<String> imageVector = getImagesFromCacheFile("imageCache", queryNumber);
        //
        try {

            DeepZoomCollection.handleTileRequest(imageVector, zoomLevel, x_Offset, y_Offset, resp);
        } catch (Exception e) {
            logger.trace("Exception while loading images: " + e.getMessage(), e);
            // TODO: for now, problems when loading images are ignored, only the exception on the console is avoided
        }
        return;
    }

    PrintStream out = new PrintStream(resp.getOutputStream(), false, "UTF-8");

    if (requestURI.endsWith(".xml")) {
        resp.setContentType("text/xml");
        int collectionNumber = 0;

        collectionNumber = Integer.parseInt(
                requestURI.substring(requestURI.indexOf("collection") + 10, requestURI.indexOf(".xml")));
        getFromCacheFile("collectionCache", collectionNumber, out);

        out.flush();
        out.close();
        return;
    }

    String q = PivotControl.decodeQuery(req.getParameter("q"));
    q = StringEscapeUtils.unescapeHtml(q);
    String uriParm = req.getParameter("uri");
    Repository repository = Global.repository;
    URI uri = null;
    if (uriParm != null)
        uri = ValueFactoryImpl.getInstance().createURI(uriParm);

    if (q != null) {
        int maxEntities = 1000;
        try {
            maxEntities = Integer.parseInt(req.getParameter("maxEntities"));
        } catch (NumberFormatException e) {
            logger.debug("wrong number format in parameter 'maxEntities'");
        }
        int maxFacets = 0;

        try {
            maxFacets = Integer.parseInt(req.getParameter("maxFacets"));
        } catch (NumberFormatException e) {
            logger.debug("wrong number format in parameter 'maxFacets'");
        }

        int hash = hash(q + maxEntities + maxFacets);

        String res = null;

        validateCache();
        res = getFromCacheFile("resultCache", hash, out);

        if (res != null) {
            logger.trace("Result loaded from cache...");

            out.close();
        } else {
            handleQuery(q, uri, repository, out, req, maxEntities, maxFacets);
            out.close();
        }
        return;
    }

}

From source file:org.exjello.mail.Exchange2003Connection.java

private void signOn() throws Exception {
    HttpClient client = getClient();/*from  w w w  .  ja v a  2 s . c  o m*/
    URL serverUrl = new URL(server);
    String host = serverUrl.getHost();
    int port = serverUrl.getPort();
    if (port == -1)
        port = serverUrl.getDefaultPort();
    AuthScope authScope = new AuthScope(host, port);

    if (username.indexOf("\\") < 0) {
        client.getState().setCredentials(authScope, new UsernamePasswordCredentials(username, password));
    } else {
        // Try to connect with NTLM authentication
        String domainUser = username.substring(username.indexOf("\\") + 1, username.length());
        String domain = username.substring(0, username.indexOf("\\"));
        client.getState().setCredentials(authScope, new NTCredentials(domainUser, password, host, domain));
    }

    boolean authenticated = false;
    OptionsMethod authTest = new OptionsMethod(server + "/exchange");
    try {
        authenticated = (client.executeMethod(authTest) < 400);
    } finally {
        try {
            InputStream stream = authTest.getResponseBodyAsStream();
            byte[] buf = new byte[65536];
            try {
                if (session.getDebug()) {
                    PrintStream log = session.getDebugOut();
                    log.println("Response Body:");
                    int count;
                    while ((count = stream.read(buf, 0, 65536)) != -1) {
                        log.write(buf, 0, count);
                    }
                    log.flush();
                    log.println();
                } else {
                    while (stream.read(buf, 0, 65536) != -1)
                        ;
                }
            } catch (Exception ignore) {
            } finally {
                try {
                    stream.close();
                } catch (Exception ignore2) {
                }
            }
        } finally {
            authTest.releaseConnection();
        }
    }
    if (!authenticated) {
        PostMethod op = new PostMethod(server + SIGN_ON_URI);
        op.setRequestHeader("Content-Type", FORM_URLENCODED_CONTENT_TYPE);
        op.addParameter("destination", server + "/exchange");
        op.addParameter("flags", "0");
        op.addParameter("username", username);
        op.addParameter("password", password);
        try {
            int status = client.executeMethod(op);
            if (status >= 400) {
                throw new IllegalStateException("Sign-on failed: " + status);
            }
        } finally {
            try {
                InputStream stream = op.getResponseBodyAsStream();
                byte[] buf = new byte[65536];
                try {
                    if (session.getDebug()) {
                        PrintStream log = session.getDebugOut();
                        log.println("Response Body:");
                        int count;
                        while ((count = stream.read(buf, 0, 65536)) != -1) {
                            log.write(buf, 0, count);
                        }
                        log.flush();
                        log.println();
                    } else {
                        while (stream.read(buf, 0, 65536) != -1)
                            ;
                    }
                } catch (Exception ignore) {
                } finally {
                    try {
                        stream.close();
                    } catch (Exception ignore2) {
                    }
                }
            } finally {
                op.releaseConnection();
            }
        }
    }
    findInbox();
}

From source file:org.codehaus.enunciate.modules.gwt.GWTDeploymentModule.java

/**
 * Reads a resource into string form.// w w  w  .j a va 2s .co  m
 *
 * @param resource The resource to read.
 * @return The string form of the resource.
 */
protected String readResource(String resource) throws IOException, EnunciateException {
    HashMap<String, Object> model = new HashMap<String, Object>();
    model.put("sample_service_method", getModelInternal().findExampleWebMethod());
    model.put("sample_resource", getModelInternal().findExampleResourceMethod());

    URL res = GWTDeploymentModule.class.getResource(resource);
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(bytes);
    try {
        processTemplate(res, model, out);
        out.flush();
        bytes.flush();
        return bytes.toString("utf-8");
    } catch (TemplateException e) {
        throw new EnunciateException(e);
    }
}

From source file:org.exjello.mail.Exchange2003Connection.java

private void doDelete(List<ExchangeMessage> messages) throws Exception {
    synchronized (this) {
        if (!isConnected()) {
            throw new IllegalStateException("Not connected.");
        }/*from w w  w . ja v  a2s.  c om*/
        HttpClient client = getClient();
        String path = inbox;
        if (!path.endsWith("/"))
            path += "/";
        ExchangeMethod op = new ExchangeMethod(BDELETE_METHOD, path);
        op.setHeader("Content-Type", XML_CONTENT_TYPE);
        op.addHeader("If-Match", "*");
        op.addHeader("Brief", "t");
        op.setRequestEntity(createDeleteEntity(messages));
        InputStream stream = null;
        try {
            int status = client.executeMethod(op);
            stream = op.getResponseBodyAsStream();
            if (status >= 300) {
                throw new IllegalStateException("Unable to delete messages.");
            }
        } finally {
            try {
                if (stream != null) {
                    byte[] buf = new byte[65536];
                    try {
                        if (session.getDebug()) {
                            PrintStream log = session.getDebugOut();
                            log.println("Response Body:");
                            int count;
                            while ((count = stream.read(buf, 0, 65536)) != -1) {
                                log.write(buf, 0, count);
                            }
                            log.flush();
                            log.println();
                        } else {
                            while (stream.read(buf, 0, 65536) != -1)
                                ;
                        }
                    } catch (Exception ignore) {
                    } finally {
                        try {
                            stream.close();
                        } catch (Exception ignore2) {
                        }
                    }
                }
            } finally {
                op.releaseConnection();
            }
        }
    }
}

From source file:org.exjello.mail.Exchange2003Connection.java

private void doMarkRead(List<ExchangeMessage> messages) throws Exception {
    synchronized (this) {
        if (!isConnected()) {
            throw new IllegalStateException("Not connected.");
        }//from   ww w  . j a  v a2s .c o m
        HttpClient client = getClient();
        String path = inbox;
        if (!path.endsWith("/"))
            path += "/";
        ExchangeMethod op = new ExchangeMethod(BPROPPATCH_METHOD, path);
        op.setHeader("Content-Type", XML_CONTENT_TYPE);
        op.addHeader("If-Match", "*");
        op.addHeader("Brief", "t");
        op.setRequestEntity(createMarkReadEntity(messages));
        InputStream stream = null;
        try {
            int status = client.executeMethod(op);
            stream = op.getResponseBodyAsStream();
            if (status >= 300) {
                throw new IllegalStateException("Unable to mark messages read.");
            }
        } finally {
            try {
                if (stream != null) {
                    byte[] buf = new byte[65536];
                    try {
                        if (session.getDebug()) {
                            PrintStream log = session.getDebugOut();
                            log.println("Response Body:");
                            int count;
                            while ((count = stream.read(buf, 0, 65536)) != -1) {
                                log.write(buf, 0, count);
                            }
                            log.flush();
                            log.println();
                        } else {
                            while (stream.read(buf, 0, 65536) != -1)
                                ;
                        }
                    } catch (Exception ignore) {
                    } finally {
                        try {
                            stream.close();
                        } catch (Exception ignore2) {
                        }
                    }
                }
            } finally {
                op.releaseConnection();
            }
        }
    }
}

From source file:org.exjello.mail.Exchange2003Connection.java

private void findInbox() throws Exception {
    inbox = null;// ww  w  .ja  v  a  2s  .  co  m
    drafts = null;
    submissionUri = null;
    sentitems = null;
    outbox = null;
    HttpClient client = getClient();
    ExchangeMethod op = new ExchangeMethod(PROPFIND_METHOD, server + "/exchange/" + mailbox);
    op.setHeader("Content-Type", XML_CONTENT_TYPE);
    op.setHeader("Depth", "0");
    op.setHeader("Brief", "t");
    op.setRequestEntity(createFindInboxEntity());
    InputStream stream = null;
    try {
        int status = client.executeMethod(op);
        stream = op.getResponseBodyAsStream();
        if (status >= 300) {
            throw new IllegalStateException("Unable to obtain inbox.");
        }
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser parser = spf.newSAXParser();
        parser.parse(stream, new DefaultHandler() {
            private final StringBuilder content = new StringBuilder();

            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                content.setLength(0);
            }

            public void characters(char[] ch, int start, int length) throws SAXException {
                content.append(ch, start, length);
            }

            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (!HTTPMAIL_NAMESPACE.equals(uri))
                    return;
                if ("inbox".equals(localName)) {
                    Exchange2003Connection.this.inbox = content.toString();
                } else if ("drafts".equals(localName)) {
                    Exchange2003Connection.this.drafts = content.toString();
                } else if ("sentitems".equals(localName)) {
                    Exchange2003Connection.this.sentitems = content.toString();
                } else if ("outbox".equals(localName)) {
                    Exchange2003Connection.this.outbox = content.toString();
                } else if ("sendmsg".equals(localName)) {
                    Exchange2003Connection.this.submissionUri = content.toString();
                }
            }
        });
        stream.close();
        stream = null;
    } finally {
        try {
            if (stream != null) {
                byte[] buf = new byte[65536];
                try {
                    if (session.getDebug()) {
                        PrintStream log = session.getDebugOut();
                        log.println("Response Body:");
                        int count;
                        while ((count = stream.read(buf, 0, 65536)) != -1) {
                            log.write(buf, 0, count);
                        }
                        log.flush();
                        log.println();
                    } else {
                        while (stream.read(buf, 0, 65536) != -1)
                            ;
                    }
                } catch (Exception ignore) {
                } finally {
                    try {
                        stream.close();
                    } catch (Exception ignore2) {
                    }
                }
            }
        } finally {
            op.releaseConnection();
        }
    }
}