Example usage for java.io PrintStream write

List of usage examples for java.io PrintStream write

Introduction

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

Prototype

public void write(byte buf[], int off, int len) 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this stream.

Usage

From source file:com.heinousdog.glassesstory.beggar.BeggarFragment.java

License:asdf

private void copyInputStreamToOutputStream(InputStream in, PrintStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int c = 0;//from w w w  .ja  v a  2  s . com
    while ((c = in.read(buffer)) != -1) {
        out.write(buffer, 0, c);
    }
}

From source file:com.juick.android.Utils.java

public static RESTResponse postForm(final Context context, final String url, ArrayList<NameValuePair> data) {
    try {//from  w  ww.  j av a 2 s  . c  om
        final String end = "\r\n";
        final String twoHyphens = "--";
        final String boundary = "****+++++******+++++++********";

        URL apiUrl = new URL(url);

        final HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection();
        conn.setConnectTimeout(10000);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.connect();
        OutputStream out = conn.getOutputStream();

        PrintStream ps = new PrintStream(out);
        int index = 0;
        byte[] block = new byte[1024];
        for (NameValuePair nameValuePair : data) {
            ps.print(twoHyphens + boundary + end);
            ps.print("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + end + end);
            final InputStream value = nameValuePair.getValue();
            while (true) {
                final int rd = value.read(block, 0, block.length);
                if (rd < 1) {
                    break;
                }
                ps.write(block, 0, rd);
            }
            value.close();
            ps.print(end);
        }
        ps.print(twoHyphens + boundary + twoHyphens + end);
        ps.close();
        boolean b = conn.getResponseCode() == 200;
        if (!b) {
            return new RESTResponse("HTTP " + conn.getResponseCode() + ": " + conn.getResponseMessage(), false,
                    null);
        } else {
            InputStream inputStream = conn.getInputStream();
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] arr = new byte[1024];
                while (true) {
                    int rd = inputStream.read(arr);
                    if (rd < 1)
                        break;
                    baos.write(arr, 0, rd);
                }
                if (conn.getHeaderField("X-GZIPCompress") != null) {
                    return new RESTResponse(null, false, baos.toString(0));
                } else {
                    return new RESTResponse(null, false, baos.toString());
                }
            } finally {
                inputStream.close();
            }
        }
    } catch (IOException e) {
        return new RESTResponse(e.toString(), false, null);
    }
}

From source file:it.greenvulcano.jmx.impl.KarafJMXEntryPoint.java

/**
 * Initializes the modeler./*from www.  ja  v a2s .  c om*/
 */
private void initModeler(Node conf) throws Exception {
    // The modeler requires an InputStream in order to configure itself,
    // so we need to serialize the configuration.

    DOMWriter writer = new DOMWriter();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PrintStream print = new PrintStream(out);

    // Read the DTD and put it in the out stream, in order to avoid the
    // exceptions
    // raised by the XML parser.
    //
    InputStream istream = getClass().getClassLoader().getResourceAsStream(MODELER_DTD);
    if (istream != null) {
        byte[] buf = new byte[2048];
        int l = 0;
        while ((l = istream.read(buf)) != -1) {
            print.write(buf, 0, l);
        }
        print.flush();
        istream.close();
    } else {
        LOG.warn(MODELER_DTD + " NOT FOUND. PLEASE, IGNORE FOLLOWING EXCEPTIONS.");
    }

    writer.write(conf, print);
    print.flush();
    print.close();

    // Prepares the input stream and initializes the modeler's Registry
    //
    ByteArrayInputStream stream = new ByteArrayInputStream(out.toByteArray());
    registry.loadDescriptors(stream);
}

From source file:org.archive.io.HeaderedArchiveRecord.java

public void dumpHttpHeader(final PrintStream stream) throws IOException {
    if (this.contentHeaderStream == null) {
        return;//from  ww  w .j av  a 2s.  c  om
    }
    // Dump the httpHeaderStream to STDOUT
    for (int available = this.contentHeaderStream.available(); this.contentHeaderStream != null
            && (available = this.contentHeaderStream.available()) > 0;) {
        // We should be in this loop only once and should do this
        // buffer allocation once.
        byte[] buffer = new byte[available];
        // The read nulls out httpHeaderStream when done with it so
        // need check for null in the loop control line.
        int read = read(buffer, 0, available);
        stream.write(buffer, 0, read);
    }
}

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 ww  w  .  j a v a  2s  .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.");
        }/*  www . jav a  2  s . 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

public InputStream getInputStream(ExchangeMessage message) throws Exception {
    synchronized (this) {
        if (!isConnected()) {
            throw new IllegalStateException("Not connected.");
        }//from  w  ww  . j  ava2 s  .  c o m
        HttpClient client = getClient();
        GetMethod op = new GetMethod(escape(message.getUrl()));
        op.setRequestHeader("Translate", "F");
        InputStream stream = null;
        try {
            int status = client.executeMethod(op);
            stream = op.getResponseBodyAsStream();
            if (status >= 300) {
                throw new IllegalStateException("Unable to obtain inbox: " + status);
            }
            final File tempFile = File.createTempFile("exmail", null, null);
            tempFile.deleteOnExit();
            OutputStream output = new FileOutputStream(tempFile);
            byte[] buf = new byte[65536];
            int count;
            while ((count = stream.read(buf, 0, 65536)) != -1) {
                output.write(buf, 0, count);
            }
            output.flush();
            output.close();
            stream.close();
            stream = null;
            return new CachedMessageStream(tempFile, (ExchangeFolder) message.getFolder());
        } 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 signOn() throws Exception {
    HttpClient client = getClient();/* w  ww .ja v  a2 s .c om*/
    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.exjello.mail.Exchange2003Connection.java

private void listFolder(DefaultHandler handler, String folder) throws Exception {
    synchronized (this) {
        if (!isConnected()) {
            throw new IllegalStateException("Not connected.");
        }/*from w  w  w . java  2s.c o  m*/
        HttpClient client = getClient();
        ExchangeMethod op = new ExchangeMethod(SEARCH_METHOD, folder);
        op.setHeader("Content-Type", XML_CONTENT_TYPE);
        if (limit > 0)
            op.setHeader("Range", "rows=0-" + limit);
        op.setHeader("Brief", "t");

        /* Mirco: Manage of custom query */
        if ((filterLastCheck == null || "".equals(filterLastCheck))
                && (filterFrom == null || "".equals(filterFrom))
                && (filterNotFrom == null || "".equals(filterNotFrom))
                && (filterTo == null || "".equals(filterTo))) {
            op.setRequestEntity(unfiltered ? createAllInboxEntity() : createUnreadInboxEntity());
        } else {
            op.setRequestEntity(
                    createCustomInboxEntity(unfiltered, filterLastCheck, filterFrom, filterNotFrom, filterTo));
        }
        InputStream stream = null;
        try {
            int status = client.executeMethod(op);
            stream = op.getResponseBodyAsStream();
            if (status >= 300) {
                throw new IllegalStateException("Unable to obtain " + folder + ".");
            }
            SAXParserFactory spf = SAXParserFactory.newInstance();
            spf.setNamespaceAware(true);
            SAXParser parser = spf.newSAXParser();
            parser.parse(stream, handler);
            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();
            }
        }
    }
}

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

private void findInbox() throws Exception {
    inbox = null;/*from  w w  w  . ja  va  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();
        }
    }
}