Search in sources :

Example 21 with NetworkEvent

use of com.codename1.io.NetworkEvent 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 22 with NetworkEvent

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

the class ImageDownloadService method createImageToFileSystem.

/**
 * Constructs an image request that will automatically populate the given Label
 * when the response arrives, it will cache the file locally.
 *
 * @param url the image URL
 * @param callback the callback that should be updated when the data arrives
 * @param destFile local file to store the data into the given path
 */
public static void createImageToFileSystem(String url, ActionListener callback, String destFile) {
    Image im = cacheImage(null, false, destFile, null, null, defaultMaintainAspectRatio);
    if (im != null) {
        callback.actionPerformed(new NetworkEvent(null, im));
        return;
    }
    // image not found on cache go and download from the url
    ImageDownloadService i = new ImageDownloadService(url, callback);
    i.cacheImages = true;
    i.destinationFile = destFile;
    i.setFailSilently(true);
    NetworkManager.getInstance().addToQueue(i);
}
Also used : NetworkEvent(com.codename1.io.NetworkEvent) EncodedImage(com.codename1.ui.EncodedImage) Image(com.codename1.ui.Image) FileEncodedImage(com.codename1.components.FileEncodedImage) StorageImage(com.codename1.components.StorageImage)

Example 23 with NetworkEvent

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

the class ImageDownloadService method createImageToStorage.

/**
 * Constructs an image request that will automatically populate the given Label
 * when the response arrives, it will cache the file locally.
 *
 * @param url the image URL
 * @param callback the callback that should be updated when the data arrives
 * @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
 */
public static void createImageToStorage(String url, ActionListener callback, String cacheId, boolean keep) {
    Image im = cacheImage(cacheId, keep, null, null, null, defaultMaintainAspectRatio);
    if (im != null) {
        callback.actionPerformed(new NetworkEvent(null, im));
        return;
    }
    // image not found on cache go and download from the url
    ImageDownloadService i = new ImageDownloadService(url, callback);
    i.cacheImages = true;
    i.cacheId = cacheId;
    i.setFailSilently(true);
    NetworkManager.getInstance().addToQueue(i);
}
Also used : NetworkEvent(com.codename1.io.NetworkEvent) EncodedImage(com.codename1.ui.EncodedImage) Image(com.codename1.ui.Image) FileEncodedImage(com.codename1.components.FileEncodedImage) StorageImage(com.codename1.components.StorageImage)

Example 24 with NetworkEvent

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

the class ImageDownloadService method handleErrorResponseCode.

/**
 * {@inheritDoc}
 */
protected void handleErrorResponseCode(int code, String message) {
    if (onErrorListeners != null) {
        NetworkEvent ne = new NetworkEvent(this, code, message);
        onErrorListeners.fireActionEvent(ne);
    }
}
Also used : NetworkEvent(com.codename1.io.NetworkEvent)

Example 25 with NetworkEvent

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

the class ImageDownloadService method handleException.

/**
 * {@inheritDoc}
 */
protected void handleException(Exception err) {
    if (onErrorListeners != null) {
        NetworkEvent ne = new NetworkEvent(this, err);
        onErrorListeners.fireActionEvent(ne);
    }
}
Also used : NetworkEvent(com.codename1.io.NetworkEvent)

Aggregations

NetworkEvent (com.codename1.io.NetworkEvent)21 ActionEvent (com.codename1.ui.events.ActionEvent)10 ActionListener (com.codename1.ui.events.ActionListener)10 Vector (java.util.Vector)8 IOException (java.io.IOException)7 Hashtable (java.util.Hashtable)7 EventDispatcher (com.codename1.ui.util.EventDispatcher)6 EncodedImage (com.codename1.ui.EncodedImage)4 FileEncodedImage (com.codename1.components.FileEncodedImage)3 StorageImage (com.codename1.components.StorageImage)3 ConnectionRequest (com.codename1.io.ConnectionRequest)3 GZConnectionRequest (com.codename1.io.gzip.GZConnectionRequest)3 Image (com.codename1.ui.Image)3 InputStreamReader (java.io.InputStreamReader)3 InfiniteProgress (com.codename1.components.InfiniteProgress)1 BufferedInputStream (com.codename1.io.BufferedInputStream)1 CharArrayReader (com.codename1.io.CharArrayReader)1 JSONParser (com.codename1.io.JSONParser)1 MultipartRequest (com.codename1.io.MultipartRequest)1 ParseException (com.codename1.l10n.ParseException)1