Search in sources :

Example 71 with URL

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

the class AndroidImplementation method getCookiesForURL.

@Override
public Vector getCookiesForURL(String url) {
    if (isUseNativeCookieStore()) {
        try {
            URI uri = new URI(url);
            CookieManager mgr = getCookieManager();
            mgr.removeExpiredCookie();
            String domain = uri.getHost();
            String cookieStr = mgr.getCookie(url);
            if (cookieStr != null) {
                String[] cookies = cookieStr.split(";");
                int len = cookies.length;
                Vector out = new Vector();
                for (int i = 0; i < len; i++) {
                    Cookie c = new Cookie();
                    String[] parts = cookies[i].split("=");
                    c.setName(parts[0].trim());
                    if (parts.length > 1) {
                        c.setValue(parts[1].trim());
                    } else {
                        c.setValue("");
                    }
                    c.setDomain(domain);
                    out.add(c);
                }
                return out;
            }
        } catch (Exception ex) {
            com.codename1.io.Log.e(ex);
        }
        return new Vector();
    }
    return super.getCookiesForURL(url);
}
Also used : URI(java.net.URI) Vector(java.util.Vector) Paint(android.graphics.Paint) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MediaException(com.codename1.media.AsyncMedia.MediaException) ParseException(java.text.ParseException) SAXException(org.xml.sax.SAXException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 72 with URL

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

the class AndroidImplementation method getSSLCertificates.

@Override
public String[] getSSLCertificates(Object connection, String url) throws IOException {
    if (connection instanceof HttpsURLConnection) {
        HttpsURLConnection conn = (HttpsURLConnection) connection;
        try {
            conn.connect();
            java.security.cert.Certificate[] certs = conn.getServerCertificates();
            String[] out = new String[certs.length * 2];
            int i = 0;
            for (java.security.cert.Certificate cert : certs) {
                {
                    MessageDigest md = MessageDigest.getInstance("SHA-256");
                    md.update(cert.getEncoded());
                    out[i++] = "SHA-256:" + dumpHex(md.digest());
                }
                {
                    MessageDigest md = MessageDigest.getInstance("SHA1");
                    md.update(cert.getEncoded());
                    out[i++] = "SHA1:" + dumpHex(md.digest());
                }
            }
            return out;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return new String[0];
}
Also used : MessageDigest(java.security.MessageDigest) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Paint(android.graphics.Paint) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MediaException(com.codename1.media.AsyncMedia.MediaException) ParseException(java.text.ParseException) SAXException(org.xml.sax.SAXException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 73 with URL

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

the class AndroidImplementation method execute.

public void execute(String url, ActionListener response) {
    if (response != null) {
        callback = new EventDispatcher();
        callback.addListener(response);
    }
    try {
        Intent intent = createIntentForURL(url);
        if (intent == null) {
            return;
        }
        if (response != null && getActivity() != null) {
            getActivity().startActivityForResult(intent, IntentResultListener.URI_SCHEME);
        } else {
            getContext().startActivity(intent);
        }
        return;
    } catch (Exception ex) {
        com.codename1.io.Log.e(ex);
    }
    try {
        if (editInProgress()) {
            stopEditing(true);
        }
        getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : EventDispatcher(com.codename1.ui.util.EventDispatcher) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MediaException(com.codename1.media.AsyncMedia.MediaException) ParseException(java.text.ParseException) SAXException(org.xml.sax.SAXException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 74 with URL

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

the class URLImage method createCachedImage.

/**
 * Creates an image that will be downloaded on the fly as necessary.  On platforms that support a native
 * image cache (e.g. Javascript), the image will be loaded directly from the native cache (i.e. it defers to the
 * platform to handle all caching considerations.  On platforms that don't have a native image cache but
 * do have a caches directory {@link FileSystemStorage#hasCachesDir()}, this will call {@link #createToFileSystem(com.codename1.ui.EncodedImage, java.lang.String, java.lang.String, com.codename1.ui.URLImage.ImageAdapter) }
 * with a file location in the caches directory.  In all other cases, this will call {@link #createToStorage(com.codename1.ui.EncodedImage, java.lang.String, java.lang.String) }.
 *
 * @param imageName The name of the image.
 * @param url the URL from which the image is fetched
 * @param placeholder the image placeholder is shown as the image is loading/downloading
 * and serves as the guideline to the size of the downloaded image.
 * @param resizeRule One of {@link #FLAG_RESIZE_FAIL}, {@link #FLAG_RESIZE_SCALE}, or {@link #FLAG_RESIZE_SCALE_TO_FILL}.
 * @return a Image that will initially just delegate to the placeholder
 */
public static Image createCachedImage(String imageName, String url, Image placeholder, int resizeRule) {
    if (Display.getInstance().supportsNativeImageCache()) {
        CachedImage im = new CachedImage(placeholder, url, resizeRule);
        im.setImageName(imageName);
        return im;
    } else {
        ImageAdapter adapter = null;
        switch(resizeRule) {
            case FLAG_RESIZE_FAIL:
                adapter = RESIZE_FAIL;
                break;
            case FLAG_RESIZE_SCALE:
                adapter = RESIZE_SCALE;
                break;
            case FLAG_RESIZE_SCALE_TO_FILL:
                adapter = RESIZE_SCALE_TO_FILL;
                break;
            default:
                adapter = RESIZE_SCALE_TO_FILL;
                break;
        }
        FileSystemStorage fs = FileSystemStorage.getInstance();
        if (fs.hasCachesDir()) {
            String name = "cn1_image_cache[" + url + "]";
            name = StringUtil.replaceAll(name, "/", "_");
            name = StringUtil.replaceAll(name, "\\", "_");
            name = StringUtil.replaceAll(name, "%", "_");
            name = StringUtil.replaceAll(name, "?", "_");
            name = StringUtil.replaceAll(name, "*", "_");
            name = StringUtil.replaceAll(name, ":", "_");
            name = StringUtil.replaceAll(name, "=", "_");
            String filePath = fs.getCachesDir() + fs.getFileSystemSeparator() + name;
            // System.out.println("Creating to file system "+filePath);
            URLImage im = createToFileSystem(EncodedImage.createFromImage(placeholder, false), filePath, url, adapter);
            im.setImageName(imageName);
            return im;
        } else {
            // System.out.println("Creating to storage ");
            URLImage im = createToStorage(EncodedImage.createFromImage(placeholder, false), "cn1_image_cache[" + url + "@" + placeholder.getWidth() + "x" + placeholder.getHeight(), url, adapter);
            im.setImageName(imageName);
            return im;
        }
    }
}
Also used : FileSystemStorage(com.codename1.io.FileSystemStorage)

Example 75 with URL

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

the class URLImage method fetch.

/**
 * Images are normally fetched from storage or network only as needed,
 * however if the download must start before the image is drawn this method
 * can be invoked. Notice that "immediately" doesn't mean synchronously, it just
 * means that the image will be added to the queue right away but probably won't be
 * available by the time the method completes.
 */
public void fetch() {
    if (fetching || imageData != null) {
        return;
    }
    fetching = true;
    try {
        locked = super.isLocked();
        if (storageFile != null) {
            if (Storage.getInstance().exists(storageFile)) {
                super.unlock();
                imageData = new byte[Storage.getInstance().entrySize(storageFile)];
                InputStream is = Storage.getInstance().createInputStream(storageFile);
                Util.readFully(is, imageData);
                resetCache();
                fetching = false;
                repaintImage = true;
                fireChangedEvent();
                return;
            }
            if (adapter != null) {
                if (url.startsWith("http://") || url.startsWith("https://")) {
                    Util.downloadImageToStorage(url, storageFile + IMAGE_SUFFIX, new SuccessCallback<Image>() {

                        public void onSucess(final Image value) {
                            imageLoader.run(new Runnable() {

                                public void run() {
                                    runAndWait(new Runnable() {

                                        public void run() {
                                            DownloadCompleted onComplete = new DownloadCompleted();
                                            onComplete.setSourceImage(value);
                                            onComplete.actionPerformed(new ActionEvent(value));
                                        }
                                    });
                                }
                            });
                        }
                    });
                } else {
                    // from file
                    loadImageFromLocalUrl(storageFile + IMAGE_SUFFIX, false);
                }
            } else {
                if (url.startsWith("http://") || url.startsWith("https://")) {
                    // Load image from http
                    Util.downloadImageToStorage(url, storageFile, new SuccessCallback<Image>() {

                        public void onSucess(final Image value) {
                            imageLoader.run(new Runnable() {

                                public void run() {
                                    runAndWait(new Runnable() {

                                        public void run() {
                                            DownloadCompleted onComplete = new DownloadCompleted();
                                            onComplete.setSourceImage(value);
                                            onComplete.actionPerformed(new ActionEvent(value));
                                        }
                                    });
                                }
                            });
                        }
                    });
                } else {
                    // load image from file system
                    loadImageFromLocalUrl(storageFile, false);
                }
            }
        } else {
            if (FileSystemStorage.getInstance().exists(fileSystemFile)) {
                super.unlock();
                imageData = new byte[(int) FileSystemStorage.getInstance().getLength(fileSystemFile)];
                InputStream is = FileSystemStorage.getInstance().openInputStream(fileSystemFile);
                Util.readFully(is, imageData);
                resetCache();
                fetching = false;
                repaintImage = true;
                fireChangedEvent();
                return;
            }
            if (adapter != null) {
                if (url.startsWith("http://") || url.startsWith("https://")) {
                    // Load image over http
                    Util.downloadImageToFileSystem(url, fileSystemFile + IMAGE_SUFFIX, new SuccessCallback<Image>() {

                        public void onSucess(final Image value) {
                            imageLoader.run(new Runnable() {

                                public void run() {
                                    runAndWait(new Runnable() {

                                        public void run() {
                                            DownloadCompleted onComplete = new DownloadCompleted();
                                            onComplete.setSourceImage(value);
                                            onComplete.actionPerformed(new ActionEvent(value));
                                        }
                                    });
                                }
                            });
                        }
                    });
                } else {
                    // load image from file system
                    loadImageFromLocalUrl(fileSystemFile + IMAGE_SUFFIX, true);
                }
            } else {
                if (url.startsWith("http://") || url.startsWith("https://")) {
                    Util.downloadImageToFileSystem(url, fileSystemFile, new SuccessCallback<Image>() {

                        public void onSucess(final Image value) {
                            imageLoader.run(new Runnable() {

                                public void run() {
                                    runAndWait(new Runnable() {

                                        public void run() {
                                            DownloadCompleted onComplete = new DownloadCompleted();
                                            onComplete.setSourceImage(value);
                                            onComplete.actionPerformed(new ActionEvent(value));
                                        }
                                    });
                                }
                            });
                        }
                    });
                } else {
                    loadImageFromLocalUrl(fileSystemFile, true);
                }
            }
        }
    } catch (IOException ioErr) {
        if (exceptionHandler != null) {
            exceptionHandler.onError(URLImage.this, ioErr);
        } else {
            throw new RuntimeException(ioErr.toString());
        }
    }
}
Also used : InputStream(java.io.InputStream) ActionEvent(com.codename1.ui.events.ActionEvent) IOException(java.io.IOException)

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