Search in sources :

Example 66 with URL

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

the class ImageDownloadService method createImageToStorage.

/**
 * Constructs an image request that will automatically populate the given list
 * when the response arrives, it will cache the file locally as a file
 * in the file storage.
 * This assumes the GenericListCellRenderer style of
 * list which relies on a map based model approach.
 *
 * @param url the image URL
 * @param targetList the list that should be updated when the data arrives
 * @param targetModel the model
 * @param targetOffset the offset within the list to insert the image
 * @param targetKey the key for the map in the target offset
 * @param cacheId a unique identifier to be used to store the image into storage
 * @param keep if set to true keeps the file in RAM once loaded
 * @param scale the scale of the image to put in the List or null
 */
private static void createImageToStorage(final String url, final Component targetList, final ListModel targetModel, final int targetOffset, final String targetKey, final String cacheId, final boolean keep, final Dimension scale, final byte priority, final Image placeholderImage, final boolean maintainAspectRatio) {
    if (Display.getInstance().isEdt()) {
        Display.getInstance().scheduleBackgroundTask(new Runnable() {

            public void run() {
                createImageToStorage(url, targetList, targetModel, targetOffset, targetKey, cacheId, keep, scale, priority, placeholderImage, maintainAspectRatio);
            }
        });
        return;
    }
    Image im = cacheImage(cacheId, keep, null, scale, placeholderImage, maintainAspectRatio);
    ImageDownloadService i = new ImageDownloadService(url, targetList, targetOffset, targetKey);
    i.targetModel = targetModel;
    i.maintainAspectRatio = maintainAspectRatio;
    if (im != null) {
        i.setEntryInListModel(targetOffset, im);
        targetList.repaint();
        return;
    }
    // image not found on cache go and download from the url
    i.cacheImages = true;
    i.cacheId = cacheId;
    i.keep = keep;
    i.toScale = scale;
    i.placeholder = placeholderImage;
    i.setPriority(priority);
    i.setFailSilently(true);
    NetworkManager.getInstance().addToQueue(i);
}
Also used : EncodedImage(com.codename1.ui.EncodedImage) Image(com.codename1.ui.Image) FileEncodedImage(com.codename1.components.FileEncodedImage) StorageImage(com.codename1.components.StorageImage)

Example 67 with URL

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

the class RSSService method readResponse.

/**
 * {@inheritDoc}
 */
protected void readResponse(InputStream input) throws IOException {
    results = new Vector();
    class FinishParsing extends RuntimeException {
    }
    XMLParser p = new XMLParser() {

        private String lastTag;

        private Hashtable current;

        private String url;

        protected boolean startTag(String tag) {
            if ("item".equalsIgnoreCase(tag) || "entry".equalsIgnoreCase(tag)) {
                if (startOffset > 0) {
                    return true;
                }
                current = new Hashtable();
                if (iconPlaceholder != null) {
                    current.put("icon", iconPlaceholder);
                }
            }
            lastTag = tag;
            return true;
        }

        protected void attribute(String tag, String attributeName, String value) {
            if (current != null) {
                if ("media:thumbnail".equalsIgnoreCase(tag) && "url".equalsIgnoreCase(attributeName)) {
                    current.put("thumb", value);
                } else {
                    if ("media:player".equalsIgnoreCase(tag) && "url".equalsIgnoreCase(attributeName)) {
                        current.put("player", value);
                    }
                }
            }
        }

        protected void textElement(String text) {
            if (lastTag != null && current != null) {
                // make "ATOM" seem like RSS
                if ("summary".equals(lastTag)) {
                    current.put("details", text);
                } else {
                    if ("content".equals(lastTag)) {
                        current.put("description", text);
                    } else {
                        current.put(lastTag, text);
                    }
                }
            }
        }

        protected void endTag(String tag) {
            if ("item".equalsIgnoreCase(tag) || "entry".equalsIgnoreCase(tag)) {
                if (startOffset > 0) {
                    startOffset--;
                    return;
                }
                results.addElement(current);
                current = null;
                if (limit > -1 && results.size() >= limit) {
                    throw new FinishParsing();
                }
            }
            if (tag.equals(lastTag)) {
                lastTag = null;
            }
        }
    };
    p.setParserCallback(this);
    input.mark(10);
    // Skip the bom marking UTF-8 in some streams
    while (input.read() != '<') {
    // input.mark(4);
    }
    int question = input.read();
    String cType = "UTF-8";
    if (question == '?') {
        // we are in an XML header, check if the encoding section exists
        StringBuilder cs = new StringBuilder();
        question = input.read();
        while (question != '>') {
            cs.append((char) question);
            question = input.read();
        }
        String str = cs.toString();
        int index = str.indexOf("encoding=\"") + 10;
        if (index > -1) {
            cType = str.substring(index, Math.max(str.indexOf("\"", index), str.indexOf("'", index)));
        }
    } else {
        // oops, continue as usual
        input.reset();
    }
    String resultType = getResponseContentType();
    if (resultType != null && resultType.indexOf("charset=") > -1) {
        cType = resultType.substring(resultType.indexOf("charset=") + 8);
    }
    try {
        int pos2 = cType.indexOf(';');
        if (pos2 > 0) {
            cType = cType.substring(0, pos2);
        }
        p.eventParser(new InputStreamReader(input, cType));
    } catch (FinishParsing ignor) {
        hasMore = true;
    }
    if (isCreatePlainTextDetails()) {
        int elementCount = results.size();
        for (int iter = 0; iter < elementCount; iter++) {
            Hashtable h = (Hashtable) results.elementAt(iter);
            String s = (String) h.get("description");
            if (s != null && !h.containsKey("details")) {
                XMLParser x = new XMLParser();
                Element e = x.parse(new CharArrayReader(("<xml>" + s + "</xml>").toCharArray()));
                Vector results = e.getTextDescendants(null, false);
                StringBuilder endResult = new StringBuilder();
                for (int i = 0; i < results.size(); i++) {
                    endResult.append(((Element) results.elementAt(i)).getText());
                }
                h.put("details", endResult.toString());
            }
        }
    }
    fireResponseListener(new NetworkEvent(this, results));
}
Also used : CharArrayReader(com.codename1.io.CharArrayReader) InputStreamReader(java.io.InputStreamReader) Hashtable(java.util.Hashtable) Element(com.codename1.xml.Element) NetworkEvent(com.codename1.io.NetworkEvent) XMLParser(com.codename1.xml.XMLParser) Vector(java.util.Vector)

Example 68 with URL

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

the class CSSBorder method backgroundImage.

/**
 * Adds one or more background images from a CSS background-image property.
 * @param cssDirective The value of the background-image property.
 * @return Self for chaining.
 */
public CSSBorder backgroundImage(String cssDirective) {
    String[] parts = Util.split(cssDirective, ",");
    List<Image> imgs = new ArrayList<Image>();
    for (String part : parts) {
        part = part.trim();
        if (part.indexOf("url(") == 0) {
            part = part.substring(4, part.length() - 1);
        }
        if (part.charAt(0) == '"' || part.charAt(0) == '"') {
            part = part.substring(1, part.length() - 1);
        }
        if (part.indexOf("/") != -1) {
            part = part.substring(part.lastIndexOf("/") + 1);
        }
        Image im = res.getImage(part);
        if (im == null) {
            try {
                im = EncodedImage.create("/" + part);
                im.setImageName(part);
            } catch (IOException ex) {
                Log.e(ex);
                throw new IllegalArgumentException("Failed to parse image: " + part);
            }
        }
        imgs.add(im);
    }
    return backgroundImage(imgs.toArray(new Image[imgs.size()]));
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) EncodedImage(com.codename1.ui.EncodedImage) Image(com.codename1.ui.Image)

Example 69 with URL

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

the class DefaultDocumentRequestHandler method resourceRequested.

private InputStream resourceRequested(final DocumentInfo docInfo, final IOCallback callback) {
    String url = docInfo.getUrl();
    visitingURL(url);
    // trim anchors
    int hash = url.indexOf('#');
    if (hash != -1) {
        url = url.substring(0, hash);
    }
    if (url.startsWith("jar://")) {
        callback.streamReady(Display.getInstance().getResourceAsStream(getClass(), docInfo.getUrl().substring(6)), docInfo);
        return null;
    } else {
        try {
            if (url.startsWith("local://")) {
                Image img = resFile.getImage(url.substring(8));
                if (img instanceof EncodedImage) {
                    callback.streamReady(new ByteArrayInputStream(((EncodedImage) img).getImageData()), docInfo);
                }
            }
            if (url.startsWith("res://")) {
                InputStream i = Display.getInstance().getResourceAsStream(getClass(), docInfo.getUrl().substring(6));
                Resources r = Resources.open(i);
                i.close();
                i = r.getData(docInfo.getParams());
                if (i != null) {
                    callback.streamReady(i, docInfo);
                } else {
                    Image img = r.getImage(docInfo.getParams());
                    if (img instanceof EncodedImage) {
                        callback.streamReady(new ByteArrayInputStream(((EncodedImage) img).getImageData()), docInfo);
                    }
                }
                return null;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return null;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Resources(com.codename1.ui.util.Resources) IOException(java.io.IOException) Image(com.codename1.ui.Image) EncodedImage(com.codename1.ui.EncodedImage) EncodedImage(com.codename1.ui.EncodedImage)

Example 70 with URL

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

the class AsyncDocumentRequestHandlerImpl method resourceRequested.

private InputStream resourceRequested(final DocumentInfo docInfo, final IOCallback callback) {
    try {
        if (docInfo.getUrl().startsWith("file://")) {
            String url = docInfo.getUrl();
            // trim anchors
            int hash = url.indexOf('#');
            if (hash != -1) {
                url = url.substring(0, hash);
            }
            callback.streamReady(FileSystemStorage.getInstance().openInputStream(url), docInfo);
            return null;
        }
    } catch (IOException ex) {
        Log.e(ex);
    }
    final Object[] response = new Object[1];
    ConnectionRequest reqest = createConnectionRequest(docInfo, callback, response);
    reqest.setPost(docInfo.isPostRequest());
    if (docInfo.isPostRequest()) {
        reqest.setUrl(docInfo.getUrl());
        reqest.setWriteRequest(true);
    } else {
        reqest.setUrl(docInfo.getFullUrl());
    }
    NetworkManager.getInstance().addToQueue(reqest);
    if (callback == null) {
        synchronized (LOCK) {
            while (response[0] == null) {
                try {
                    LOCK.wait(50);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
            if (response[0] instanceof InputStream) {
                return (InputStream) response[0];
            }
            // we need a better way to handle this...
            if (response[0] instanceof Throwable) {
                ((Throwable) response[0]).printStackTrace();
            }
        }
    }
    return null;
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) InputStream(java.io.InputStream) 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