Search in sources :

Example 51 with URL

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

the class CodenameOneImplementation method setBrowserURL.

/**
 * Sets the page URL, jar: URL's must be supported by the implementation
 * @param browserPeer browser instance
 * @param url  the URL
 */
public void setBrowserURL(PeerComponent browserPeer, String url) {
    // load from jar:// URL's
    try {
        InputStream i = Display.getInstance().getResourceAsStream(getClass(), url.substring(6));
        if (i == null) {
            System.out.println("Local resource not found: " + url);
            return;
        }
        byte[] buffer = new byte[4096];
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        int size = i.read(buffer);
        while (size > -1) {
            bo.write(buffer, 0, size);
            size = i.read(buffer);
        }
        i.close();
        bo.close();
        String htmlText = new String(bo.toByteArray(), "UTF-8");
        String baseUrl = url.substring(0, url.lastIndexOf('/'));
        setBrowserPage(browserPeer, htmlText, baseUrl);
        return;
    } catch (IOException ex) {
        Log.e(ex);
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) DataInputStream(java.io.DataInputStream) TarInputStream(com.codename1.io.tar.TarInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 52 with URL

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

the class CodenameOneImplementation method getCookiesForURL.

/**
 * Returns the cookies for this URL
 *
 * @param url the url on which we are checking for cookies
 * @return the cookies to submit to the given URL
 */
public Vector getCookiesForURL(String url) {
    Vector response = null;
    if (Cookie.isAutoStored()) {
        cookies = (Hashtable) Storage.getInstance().readObject(Cookie.STORAGE_NAME);
    }
    String protocol = "";
    int pos = -1;
    if ((pos = url.indexOf(":")) >= 0) {
        protocol = url.substring(0, pos);
    }
    boolean isHttp = ("http".equals(protocol) || "https".equals(protocol));
    boolean isSecure = "https".equals(protocol);
    String path = getURLPath(url);
    if (cookies != null && cookies.size() > 0) {
        String domain = getURLDomain(url);
        Enumeration e = cookies.keys();
        while (e.hasMoreElements()) {
            String domainKey = (String) e.nextElement();
            if (domain.indexOf(domainKey) > -1) {
                Hashtable h = (Hashtable) cookies.get(domainKey);
                if (h != null) {
                    Enumeration enumCookies = h.elements();
                    if (response == null) {
                        response = new Vector();
                    }
                    while (enumCookies.hasMoreElements()) {
                        Cookie nex = (Cookie) enumCookies.nextElement();
                        if (nex.isHttpOnly() && !isHttp) {
                            continue;
                        }
                        if (nex.isSecure() && !isSecure) {
                            continue;
                        }
                        if (path.indexOf(nex.getPath()) != 0) {
                            continue;
                        }
                        response.addElement(nex);
                    }
                }
            }
        }
    }
    return response;
}
Also used : Cookie(com.codename1.io.Cookie) Enumeration(java.util.Enumeration) Hashtable(java.util.Hashtable) Vector(java.util.Vector)

Example 53 with URL

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

the class Oauth2 method handleURL.

private void handleURL(String url, WebBrowser web, final ActionListener al, final Form frm, final Form backToForm, final Dialog progress) {
    if ((url.startsWith(redirectURI))) {
        if (progress != null && Display.getInstance().getCurrent() == progress) {
            progress.dispose();
        }
        if (web != null) {
            web.stop();
        }
        // remove the browser component.
        if (login != null) {
            login.removeAll();
            login.revalidate();
        }
        if (url.indexOf("code=") > -1) {
            Hashtable params = getParamsFromURL(url);
            handleRedirectURLParams(params);
            class TokenRequest extends ConnectionRequest {

                boolean callbackCalled;

                protected void readResponse(InputStream input) throws IOException {
                    byte[] tok = Util.readInputStream(input);
                    String t = new String(tok);
                    boolean expiresRelative = true;
                    if (t.startsWith("{")) {
                        JSONParser p = new JSONParser();
                        Map map = p.parseJSON(new StringReader(t));
                        handleTokenRequestResponse(map);
                    } else {
                        handleTokenRequestResponse(t);
                    }
                    if (login != null) {
                        login.dispose();
                    }
                }

                protected void handleException(Exception err) {
                    if (backToForm != null && !callbackCalled) {
                        backToForm.showBack();
                    }
                    if (al != null) {
                        if (!callbackCalled) {
                            callbackCalled = true;
                            al.actionPerformed(new ActionEvent(err, ActionEvent.Type.Exception));
                        }
                    }
                }

                protected void postResponse() {
                    if (backToParent && backToForm != null && !callbackCalled) {
                        backToForm.showBack();
                    }
                    if (al != null) {
                        if (!callbackCalled) {
                            callbackCalled = true;
                            if (getResponseCode() >= 200 && getResponseCode() < 300) {
                                al.actionPerformed(new ActionEvent(new AccessToken(token, expires, refreshToken, identityToken), ActionEvent.Type.Response));
                            } else {
                                al.actionPerformed(new ActionEvent(new IOException(getResponseErrorMessage()), ActionEvent.Type.Exception));
                            }
                        }
                    }
                }
            }
            ;
            final TokenRequest req = new TokenRequest();
            req.setReadResponseForErrors(true);
            req.setUrl(tokenRequestURL);
            req.setPost(true);
            req.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            req.addArgument("client_id", clientId);
            req.addArgument("redirect_uri", redirectURI);
            req.addArgument("client_secret", clientSecret);
            if (params.containsKey("cn1_refresh_token")) {
                req.addArgument("grant_type", "refresh_token");
                req.addArgument("refresh_token", (String) params.get("code"));
            } else {
                req.addArgument("code", (String) params.get("code"));
                req.addArgument("grant_type", "authorization_code");
            }
            NetworkManager.getInstance().addToQueue(req);
        } else if (url.indexOf("error_reason=") > -1) {
            Hashtable table = getParamsFromURL(url);
            String error = (String) table.get("error_reason");
            if (login != null) {
                login.dispose();
            }
            if (backToForm != null) {
                backToForm.showBack();
            }
            if (al != null) {
                al.actionPerformed(new ActionEvent(new IOException(error), ActionEvent.Type.Exception));
            }
        } else {
            boolean success = url.indexOf("#") > -1;
            if (success) {
                String accessToken = url.substring(url.indexOf("#") + 1);
                if (accessToken.indexOf("&") > 0) {
                    token = accessToken.substring(accessToken.indexOf("=") + 1, accessToken.indexOf("&"));
                } else {
                    token = accessToken.substring(accessToken.indexOf("=") + 1);
                }
                if (login != null) {
                    login.dispose();
                }
                if (backToParent && backToForm != null) {
                    backToForm.showBack();
                }
                if (al != null) {
                    al.actionPerformed(new ActionEvent(new AccessToken(token, expires), ActionEvent.Type.Response));
                }
            }
        }
    } else {
        if (frm != null && Display.getInstance().getCurrent() != frm) {
            progress.dispose();
            frm.show();
        }
    }
}
Also used : Hashtable(java.util.Hashtable) InputStream(java.io.InputStream) ActionEvent(com.codename1.ui.events.ActionEvent) IOException(java.io.IOException) IOException(java.io.IOException) StringReader(com.codename1.util.regex.StringReader) HashMap(java.util.HashMap) Map(java.util.Map)

Example 54 with URL

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

the class ConnectionRequest method performOperationComplete.

/**
 * Performs the actual network request on behalf of the network manager
 * @return true if the operation completed, false if the network request is scheduled to be retried.
 */
boolean performOperationComplete() throws IOException {
    if (shouldStop()) {
        return true;
    }
    if (cacheMode == CachingMode.OFFLINE || cacheMode == CachingMode.OFFLINE_FIRST) {
        InputStream is = getCachedData();
        if (is != null) {
            readResponse(is);
            Util.cleanup(is);
            return true;
        } else {
            if (cacheMode == CachingMode.OFFLINE) {
                responseCode = 404;
                throw new IOException("File unavilable in cache");
            }
        }
    }
    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());
        }
        _connection = connection;
        if (shouldStop()) {
            return true;
        }
        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() && // empty POST bodies.
        !Util.getImplementation().checkSSLCertificatesRequiresCallbackFromNative()) {
            sslCertificates = getSSLCertificatesImpl(connection, url);
            checkSSLCertificates(sslCertificates);
            if (shouldStop()) {
                return true;
            }
        }
        if (isWriteRequest()) {
            progress = NetworkEvent.PROGRESS_TYPE_OUTPUT;
            output = impl.openOutputStream(connection);
            if (shouldStop()) {
                return true;
            }
            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 if (requestBodyData != null) {
                requestBodyData.appendTo(output);
            } else {
                buildRequestBody(output);
            }
            if (shouldStop()) {
                return true;
            }
            if (output instanceof BufferedOutputStream) {
                ((BufferedOutputStream) output).flushBuffer();
                if (shouldStop()) {
                    return true;
                }
            }
        }
        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 true;
        }
        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 false;
                }
                return true;
            }
            responseErrorMessge = impl.getResponseMessage(connection);
            handleErrorResponseCode(responseCode, responseErrorMessge);
            if (!isReadResponseForErrors()) {
                return true;
            }
        }
        responseContentType = getHeader(connection, "Content-Type");
        if (cacheMode == CachingMode.SMART || cacheMode == CachingMode.MANUAL || cacheMode == CachingMode.OFFLINE_FIRST) {
            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 true;
            }
            if (input instanceof BufferedInputStream) {
                if (NetworkManager.getInstance().hasProgressListeners()) {
                    ((BufferedInputStream) input).setProgressListener(this);
                }
                ((BufferedInputStream) input).setYield(getYield());
            }
            if (!post && (cacheMode == CachingMode.SMART || cacheMode == CachingMode.OFFLINE_FIRST) && 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()) {
                if (input != null)
                    input.close();
            }
        }
    } 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;
        _connection = null;
    }
    if (!isKilled()) {
        Display.getInstance().callSerially(new Runnable() {

            public void run() {
                postResponse();
            }
        });
    }
    return true;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) 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 55 with URL

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

the class VServAds method getPendingAd.

/**
 * {@inheritDoc}
 */
protected Component getPendingAd() {
    if (imageURL == null) {
        return null;
    }
    if (renderNotify != null && renderNotify.length() > 0) {
        ConnectionRequest c = new ConnectionRequest();
        c.setFailSilently(true);
        c.setUrl(renderNotify);
        c.setPost(false);
        NetworkManager.getInstance().addToQueue(c);
    }
    if ("image".equalsIgnoreCase(contentType)) {
        Button adComponent = new Button() {

            public void setIcon(Image icon) {
                if (icon != null && isScaleMode()) {
                    icon = icon.scaledWidth(Display.getInstance().getDisplayWidth());
                }
                super.setIcon(icon);
            }
        };
        adComponent.setUIID("Container");
        adComponent.getStyle().setBgColor(backgroundColor);
        adComponent.getStyle().setOpacity(0xff);
        ImageDownloadService imd = new ImageDownloadService(imageURL, adComponent);
        NetworkManager.getInstance().addToQueueAndWait(imd);
        /*adComponent.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    Display.getInstance().execute(getAdDestination());
                }
            });*/
        return adComponent;
    } else {
        WebBrowser wb = new WebBrowser();
        if (wb.getInternal() instanceof BrowserComponent) {
            BrowserComponent bc = (BrowserComponent) wb.getInternal();
            bc.setBrowserNavigationCallback(new BrowserNavigationCallback() {

                public boolean shouldNavigate(final String url) {
                    unlock(new ActionListener() {

                        public void actionPerformed(ActionEvent evt) {
                            Display.getInstance().execute(url);
                        }
                    });
                    return false;
                }
            });
        }
        wb.setURL(imageURL);
        return wb;
    }
}
Also used : ImageDownloadService(com.codename1.io.services.ImageDownloadService) ConnectionRequest(com.codename1.io.ConnectionRequest) WebBrowser(com.codename1.components.WebBrowser) ActionListener(com.codename1.ui.events.ActionListener) ActionEvent(com.codename1.ui.events.ActionEvent) BrowserNavigationCallback(com.codename1.ui.events.BrowserNavigationCallback)

Aggregations

IOException (java.io.IOException)33 InputStream (java.io.InputStream)18 ConnectionRequest (com.codename1.io.ConnectionRequest)12 ActionEvent (com.codename1.ui.events.ActionEvent)12 ByteArrayInputStream (java.io.ByteArrayInputStream)12 File (java.io.File)11 Form (com.codename1.ui.Form)10 OutputStream (java.io.OutputStream)10 Image (com.codename1.ui.Image)9 Vector (java.util.Vector)9 EncodedImage (com.codename1.ui.EncodedImage)8 InvocationTargetException (java.lang.reflect.InvocationTargetException)8 URISyntaxException (java.net.URISyntaxException)7 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)5 RemoteException (android.os.RemoteException)5 BufferedInputStream (com.codename1.io.BufferedInputStream)5 FileSystemStorage (com.codename1.io.FileSystemStorage)5 MediaException (com.codename1.media.AsyncMedia.MediaException)5 ActionListener (com.codename1.ui.events.ActionListener)5 FileInputStream (java.io.FileInputStream)5