Search in sources :

Example 6 with BufferedOutputStream

use of com.codename1.io.BufferedOutputStream in project CodenameOne by codenameone.

the class ConnectionRequest method performOperation.

/**
 * Performs the actual network request on behalf of the network manager
 */
void performOperation() throws IOException {
    if (shouldStop()) {
        return;
    }
    if (cacheMode == CachingMode.OFFLINE) {
        InputStream is = getCachedData();
        if (is != null) {
            readResponse(is);
            Util.cleanup(is);
        } else {
            responseCode = 404;
            throw new IOException("File unavilable in cache");
        }
        return;
    }
    CodenameOneImplementation impl = Util.getImplementation();
    Object connection = null;
    input = null;
    output = null;
    redirecting = false;
    try {
        String actualUrl = createRequestURL();
        if (timeout > 0) {
            connection = impl.connect(actualUrl, isReadRequest(), isPost() || isWriteRequest(), timeout);
        } else {
            connection = impl.connect(actualUrl, isReadRequest(), isPost() || isWriteRequest());
        }
        if (shouldStop()) {
            return;
        }
        initConnection(connection);
        if (httpMethod != null) {
            impl.setHttpMethod(connection, httpMethod);
        }
        if (isCookiesEnabled()) {
            Vector v = impl.getCookiesForURL(actualUrl);
            if (v != null) {
                int c = v.size();
                if (c > 0) {
                    StringBuilder cookieStr = new StringBuilder();
                    Cookie first = (Cookie) v.elementAt(0);
                    cookieSent(first);
                    cookieStr.append(first.getName());
                    cookieStr.append("=");
                    cookieStr.append(first.getValue());
                    for (int iter = 1; iter < c; iter++) {
                        Cookie current = (Cookie) v.elementAt(iter);
                        cookieStr.append(";");
                        cookieStr.append(current.getName());
                        cookieStr.append("=");
                        cookieStr.append(current.getValue());
                        cookieSent(current);
                    }
                    impl.setHeader(connection, cookieHeader, initCookieHeader(cookieStr.toString()));
                } else {
                    String s = initCookieHeader(null);
                    if (s != null) {
                        impl.setHeader(connection, cookieHeader, s);
                    }
                }
            } else {
                String s = initCookieHeader(null);
                if (s != null) {
                    impl.setHeader(connection, cookieHeader, s);
                }
            }
        }
        if (checkSSLCertificates && canGetSSLCertificates()) {
            sslCertificates = getSSLCertificatesImpl(connection, url);
            checkSSLCertificates(sslCertificates);
            if (shouldStop()) {
                return;
            }
        }
        if (isWriteRequest()) {
            progress = NetworkEvent.PROGRESS_TYPE_OUTPUT;
            output = impl.openOutputStream(connection);
            if (shouldStop()) {
                return;
            }
            if (NetworkManager.getInstance().hasProgressListeners() && output instanceof BufferedOutputStream) {
                ((BufferedOutputStream) output).setProgressListener(this);
            }
            if (requestBody != null) {
                if (shouldWriteUTFAsGetBytes()) {
                    output.write(requestBody.getBytes("UTF-8"));
                } else {
                    OutputStreamWriter w = new OutputStreamWriter(output, "UTF-8");
                    w.write(requestBody);
                }
            } else {
                buildRequestBody(output);
            }
            if (shouldStop()) {
                return;
            }
            if (output instanceof BufferedOutputStream) {
                ((BufferedOutputStream) output).flushBuffer();
                if (shouldStop()) {
                    return;
                }
            }
        }
        timeSinceLastUpdate = System.currentTimeMillis();
        responseCode = impl.getResponseCode(connection);
        if (isCookiesEnabled()) {
            String[] cookies = impl.getHeaderFields("Set-Cookie", connection);
            if (cookies != null && cookies.length > 0) {
                ArrayList cook = new ArrayList();
                int clen = cookies.length;
                for (int iter = 0; iter < clen; iter++) {
                    Cookie coo = parseCookieHeader(cookies[iter]);
                    if (coo != null) {
                        cook.add(coo);
                        cookieReceived(coo);
                    }
                }
                impl.addCookie((Cookie[]) cook.toArray(new Cookie[cook.size()]));
            }
        }
        if (responseCode == 304 && cacheMode != CachingMode.OFF) {
            cacheUnmodified();
            return;
        }
        if (responseCode - 200 < 0 || responseCode - 200 > 100) {
            readErrorCodeHeaders(connection);
            // redirect to new location
            if (followRedirects && (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307)) {
                String uri = impl.getHeaderField("location", connection);
                if (!(uri.startsWith("http://") || uri.startsWith("https://"))) {
                    // relative URI's in the location header are illegal but some sites mistakenly use them
                    url = Util.relativeToAbsolute(url, uri);
                } else {
                    url = uri;
                }
                if (requestArguments != null && url.indexOf('?') > -1) {
                    requestArguments.clear();
                }
                if ((responseCode == 302 || responseCode == 303)) {
                    if (this.post && shouldConvertPostToGetOnRedirect()) {
                        this.post = false;
                        setWriteRequest(false);
                    }
                }
                impl.cleanup(output);
                impl.cleanup(connection);
                connection = null;
                output = null;
                if (!onRedirect(url)) {
                    redirecting = true;
                    retry();
                }
                return;
            }
            responseErrorMessge = impl.getResponseMessage(connection);
            handleErrorResponseCode(responseCode, responseErrorMessge);
            if (!isReadResponseForErrors()) {
                return;
            }
        }
        responseContentType = getHeader(connection, "Content-Type");
        if (cacheMode == CachingMode.SMART || cacheMode == CachingMode.MANUAL) {
            String last = getHeader(connection, "Last-Modified");
            String etag = getHeader(connection, "ETag");
            Preferences.set("cn1MSince" + createRequestURL(), last);
            Preferences.set("cn1Etag" + createRequestURL(), etag);
        }
        readHeaders(connection);
        contentLength = impl.getContentLength(connection);
        timeSinceLastUpdate = System.currentTimeMillis();
        progress = NetworkEvent.PROGRESS_TYPE_INPUT;
        if (isReadRequest()) {
            input = impl.openInputStream(connection);
            if (shouldStop()) {
                return;
            }
            if (input instanceof BufferedInputStream) {
                if (NetworkManager.getInstance().hasProgressListeners()) {
                    ((BufferedInputStream) input).setProgressListener(this);
                }
                ((BufferedInputStream) input).setYield(getYield());
            }
            if (!post && cacheMode == CachingMode.SMART && destinationFile == null && destinationStorage == null) {
                byte[] d = Util.readInputStream(input);
                OutputStream os = FileSystemStorage.getInstance().openOutputStream(getCacheFileName());
                os.write(d);
                os.close();
                readResponse(new ByteArrayInputStream(d));
            } else {
                readResponse(input);
            }
            if (shouldAutoCloseResponse()) {
                input.close();
            }
            input = null;
        }
    } finally {
        // always cleanup connections/streams even in case of an exception
        impl.cleanup(output);
        impl.cleanup(input);
        impl.cleanup(connection);
        timeSinceLastUpdate = -1;
        input = null;
        output = null;
        connection = null;
    }
    if (!isKilled()) {
        Display.getInstance().callSerially(new Runnable() {

            public void run() {
                postResponse();
            }
        });
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) OutputStreamWriter(java.io.OutputStreamWriter) Vector(java.util.Vector) CodenameOneImplementation(com.codename1.impl.CodenameOneImplementation)

Example 7 with BufferedOutputStream

use of com.codename1.io.BufferedOutputStream in project CodenameOne by codenameone.

the class JavaSEPort method openOutputStream.

/**
 * @inheritDoc
 */
public OutputStream openOutputStream(Object connection, int offset) throws IOException {
    RandomAccessFile rf = new RandomAccessFile(unfile((String) connection), "rw");
    rf.seek(offset);
    FileOutputStream fc = new FileOutputStream(rf.getFD());
    BufferedOutputStream o = new BufferedOutputStream(fc, (String) connection);
    o.setConnection(rf);
    return o;
}
Also used : BufferedOutputStream(com.codename1.io.BufferedOutputStream)

Example 8 with BufferedOutputStream

use of com.codename1.io.BufferedOutputStream in project CodenameOne by codenameone.

the class JavaSEPort method openOutputStream.

/**
 * @inheritDoc
 */
public OutputStream openOutputStream(Object connection) throws IOException {
    if (connection instanceof String) {
        FileOutputStream fc = new FileOutputStream(unfile((String) connection));
        BufferedOutputStream o = new BufferedOutputStream(fc, (String) connection);
        return o;
    }
    if (netMonitor != null || slowConnectionMode || disconnectedMode) {
        final NetworkRequestObject nr = getByConnection((URLConnection) connection);
        if (nr != null || slowConnectionMode || disconnectedMode) {
            if (disconnectedMode) {
                throw new IOException("Unreachable");
            }
            if (nr != null) {
                nr.setRequestBody("");
            }
            HttpURLConnection con = (HttpURLConnection) connection;
            OutputStream o = new BufferedOutputStream(con.getOutputStream()) {

                public void write(byte[] b, int off, int len) throws IOException {
                    super.write(b, off, len);
                    if (nr != null) {
                        nr.setRequestBody(nr.getRequestBody() + new String(b, off, len));
                    }
                    if (slowConnectionMode) {
                        try {
                            Thread.sleep(250);
                        } catch (Exception e) {
                        }
                    }
                    if (disconnectedMode) {
                        throw new IOException("Unreachable");
                    }
                }
            };
            return o;
        }
    }
    return new BufferedOutputStream(((URLConnection) connection).getOutputStream());
}
Also used : BufferedOutputStream(com.codename1.io.BufferedOutputStream) BufferedOutputStream(com.codename1.io.BufferedOutputStream) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) EOFException(java.io.EOFException) FontFormatException(java.awt.FontFormatException)

Example 9 with BufferedOutputStream

use of com.codename1.io.BufferedOutputStream in project CodenameOne by codenameone.

the class GameCanvasImplementation method openOutputStream.

/**
 * @inheritDoc
 */
public OutputStream openOutputStream(Object connection) throws IOException {
    if (connection instanceof String) {
        FileConnection fc = (FileConnection) Connector.open((String) connection, Connector.READ_WRITE);
        if (!fc.exists()) {
            fc.create();
        }
        BufferedOutputStream o = new BufferedOutputStream(fc.openOutputStream(), (String) connection);
        o.setConnection(fc);
        return o;
    }
    return new BufferedOutputStream(((HttpConnection) connection).openOutputStream(), ((HttpConnection) connection).getURL());
}
Also used : BufferedOutputStream(com.codename1.io.BufferedOutputStream) FileConnection(javax.microedition.io.file.FileConnection)

Example 10 with BufferedOutputStream

use of com.codename1.io.BufferedOutputStream in project CodenameOne by codenameone.

the class BlackBerryImplementation method openOutputStream.

/**
 * @inheritDoc
 */
public OutputStream openOutputStream(Object connection) throws IOException {
    if (connection instanceof String) {
        FileConnection fc = (FileConnection) Connector.open((String) connection, Connector.READ_WRITE);
        if (!fc.exists()) {
            fc.create();
        }
        BufferedOutputStream o = new BufferedOutputStream(fc.openOutputStream(), (String) connection);
        o.setConnection(fc);
        return o;
    }
    OutputStream os = new BlackBerryOutputStream(((HttpConnection) connection).openOutputStream());
    return new BufferedOutputStream(os, ((HttpConnection) connection).getURL());
}
Also used : DataOutputStream(java.io.DataOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(com.codename1.io.BufferedOutputStream) OutputStream(java.io.OutputStream) BufferedOutputStream(com.codename1.io.BufferedOutputStream) FileConnection(javax.microedition.io.file.FileConnection)

Aggregations

BufferedOutputStream (com.codename1.io.BufferedOutputStream)10 OutputStream (java.io.OutputStream)4 FileConnection (javax.microedition.io.file.FileConnection)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 FileOutputStream (java.io.FileOutputStream)2 CodenameOneImplementation (com.codename1.impl.CodenameOneImplementation)1 FontFormatException (java.awt.FontFormatException)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 DataOutputStream (java.io.DataOutputStream)1 EOFException (java.io.EOFException)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 RandomAccessFile (java.io.RandomAccessFile)1 SQLException (java.sql.SQLException)1 ParseException (java.text.ParseException)1 ArrayList (java.util.ArrayList)1 Vector (java.util.Vector)1 HttpConnection (javax.microedition.io.HttpConnection)1