Search in sources :

Example 1 with BufferedInputStream

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

the class BlackBerryImplementation method openInputStream.

/**
 * @inheritDoc
 */
public InputStream openInputStream(Object connection) throws IOException {
    if (connection instanceof String) {
        FileConnection fc = (FileConnection) Connector.open((String) connection, Connector.READ);
        BufferedInputStream o = new BufferedInputStream(fc.openInputStream(), (String) connection);
        o.setConnection(fc);
        return o;
    }
    return new BufferedInputStream(((HttpConnection) connection).openInputStream(), ((HttpConnection) connection).getURL());
}
Also used : BufferedInputStream(com.codename1.io.BufferedInputStream) FileConnection(javax.microedition.io.file.FileConnection)

Example 2 with BufferedInputStream

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

the class FacebookRESTService method readResponse.

protected void readResponse(InputStream input) throws IOException {
    // BufferedInputStream i = new BufferedInputStream(new InputStreamReader(input, ));
    BufferedInputStream i;
    if (input instanceof BufferedInputStream) {
        i = (BufferedInputStream) input;
    } else {
        i = new BufferedInputStream(input);
    }
    i.setYield(-1);
    InputStreamReader reader = new InputStreamReader(i, "UTF-8");
    JSONParser.parse(reader, this);
    Util.cleanup(reader);
    if (stack.size() > 0) {
        fireResponseListener(new NetworkEvent(this, stack.elementAt(0)));
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) BufferedInputStream(com.codename1.io.BufferedInputStream) NetworkEvent(com.codename1.io.NetworkEvent)

Example 3 with BufferedInputStream

use of com.codename1.io.BufferedInputStream 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 4 with BufferedInputStream

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

the class JavaSEPort method openInputStream.

/**
 * @inheritDoc
 */
public InputStream openInputStream(Object connection) throws IOException {
    if (connection instanceof String) {
        FileInputStream fc = new FileInputStream(unfile((String) connection));
        BufferedInputStream o = new BufferedInputStream(fc, (String) connection);
        return o;
    }
    if (netMonitor != null || slowConnectionMode || disconnectedMode) {
        final NetworkRequestObject nr = getByConnection((URLConnection) connection);
        if (nr != null || slowConnectionMode || disconnectedMode) {
            if (slowConnectionMode) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }
            if (disconnectedMode) {
                throw new IOException("Unreachable");
            }
            HttpURLConnection con = (HttpURLConnection) connection;
            String headers = "";
            Map<String, List<String>> map = con.getHeaderFields();
            for (String header : map.keySet()) {
                headers += header + "=" + map.get(header) + "\n";
            }
            if (nr != null) {
                nr.setResponseHeaders(headers);
                nr.setResponseBody("");
            }
            InputStream is;
            if (con.getResponseCode() >= 200 && con.getResponseCode() < 300) {
                is = con.getInputStream();
            } else {
                is = con.getErrorStream();
            }
            InputStream i = new BufferedInputStream(is) {

                public synchronized int read(byte[] b, int off, int len) throws IOException {
                    int s = super.read(b, off, len);
                    if (nr != null) {
                        if (s > -1) {
                            nr.setResponseBody(nr.getResponseBody() + new String(b, off, len));
                        }
                    }
                    if (slowConnectionMode) {
                        try {
                            Thread.sleep(len);
                        } catch (Exception e) {
                        }
                    }
                    if (disconnectedMode) {
                        throw new IOException("Unreachable");
                    }
                    return s;
                }
            };
            return i;
        }
    }
    if (connection instanceof HttpURLConnection) {
        HttpURLConnection ht = (HttpURLConnection) connection;
        if (ht.getResponseCode() < 400) {
            return new BufferedInputStream(ht.getInputStream());
        }
        return new BufferedInputStream(ht.getErrorStream());
    } else {
        return new BufferedInputStream(((URLConnection) connection).getInputStream());
    }
}
Also used : BufferedInputStream(com.codename1.io.BufferedInputStream) BufferedInputStream(com.codename1.io.BufferedInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipInputStream(java.util.zip.ZipInputStream) List(java.util.List) NodeList(org.w3c.dom.NodeList) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) EOFException(java.io.EOFException) FontFormatException(java.awt.FontFormatException) Point(java.awt.Point)

Example 5 with BufferedInputStream

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

the class IOSImplementation method openInputStream.

/**
 * @inheritDoc
 */
public InputStream openInputStream(Object connection) throws IOException {
    if (connection instanceof String) {
        BufferedInputStream o = new BufferedInputStream(new NSFileInputStream((String) connection), (String) connection);
        return o;
    }
    NetworkConnection n = (NetworkConnection) connection;
    n.ensureConnection();
    return new BufferedInputStream(n);
}
Also used : BufferedInputStream(com.codename1.io.BufferedInputStream)

Aggregations

BufferedInputStream (com.codename1.io.BufferedInputStream)6 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InputStream (java.io.InputStream)2 FileConnection (javax.microedition.io.file.FileConnection)2 CodenameOneImplementation (com.codename1.impl.CodenameOneImplementation)1 NetworkEvent (com.codename1.io.NetworkEvent)1 FontFormatException (java.awt.FontFormatException)1 Point (java.awt.Point)1 EOFException (java.io.EOFException)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 OutputStream (java.io.OutputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 HttpURLConnection (java.net.HttpURLConnection)1 SQLException (java.sql.SQLException)1 ParseException (java.text.ParseException)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Vector (java.util.Vector)1