Search in sources :

Example 31 with URL

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

the class CodenameOneImplementation method setBrowserPageInHierarchy.

/**
 * Sets a relative URL from the html hierarchy
 *
 * @param browserPeer the peer component
 * @param url the url relative to the HTML directory
 */
public void setBrowserPageInHierarchy(PeerComponent browserPeer, String url) throws IOException {
    installTar();
    FileSystemStorage fs = FileSystemStorage.getInstance();
    String tardir = fs.getAppHomePath() + "cn1html";
    if (tardir.startsWith("/")) {
        tardir = "file://" + tardir;
    }
    if (url.startsWith("/")) {
        setBrowserURL(browserPeer, tardir + url);
    } else {
        setBrowserURL(browserPeer, tardir + "/" + url);
    }
}
Also used : FileSystemStorage(com.codename1.io.FileSystemStorage)

Example 32 with URL

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

the class CodenameOneImplementation method downloadImageToCache.

/**
 * Downloads an image from a URL to the cache. Platforms
 * that support a native image cache {@link #supportsNativeImageCache() } (e.g. Javascript) override this method to defer to the
 * platform's handling of cached images.  Platforms that have a caches directory ({@link FileSystemStorage#hasCachesDir() }
 * will use that directory to cache the image.  Other platforms will just download to storage.
 *
 * @param url The URL of the image to download.
 * @param onSuccess Callback on success.
 * @param onFail Callback on fail.
 *
 * @see URLImage#createToCache(com.codename1.ui.EncodedImage, java.lang.String, com.codename1.ui.URLImage.ImageAdapter)
 */
public void downloadImageToCache(String url, SuccessCallback<Image> onSuccess, final FailureCallback<Image> onFail) {
    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;
        // We use Util.downloadImageToFileSystem rather than CodenameOneImplementation.downloadImageToFileSystem
        // because we want it to try to load from file system first.
        Util.downloadImageToFileSystem(url, filePath, onSuccess, onFail);
    } else {
        // We use Util.downloadImageToStorage rather than CodenameOneImplementation.downloadImageToStorage
        // because we want it to try to load from storage first.
        Util.downloadImageToStorage(url, "cn1_image_cache[" + url + "]", onSuccess, onFail);
    }
}
Also used : FileSystemStorage(com.codename1.io.FileSystemStorage)

Example 33 with URL

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

the class VServAds method createAdRequest.

/**
 * {@inheritDoc}
 */
protected ConnectionRequest createAdRequest() {
    ConnectionRequest con = new ConnectionRequest() {

        protected void handleErrorResponseCode(int code, String message) {
            failed = true;
        }

        protected void handleException(Exception err) {
            failed = true;
            Log.e(err);
        }

        private String getString(Hashtable h, String n) {
            Object v = h.get(n);
            if (v == null) {
                return null;
            }
            if (v instanceof Vector) {
                return (String) ((Vector) v).elementAt(0);
            }
            return (String) v;
        }

        protected void readResponse(InputStream input) throws IOException {
            JSONParser parser = new JSONParser();
            Hashtable h = parser.parse(new InputStreamReader(input, "UTF-8"));
            if (h.size() == 0) {
                return;
            }
            backgroundColor = Integer.parseInt((String) ((Hashtable) ((Vector) h.get("style")).elementAt(0)).get("background-color"), 16);
            Hashtable actionHash = ((Hashtable) ((Vector) h.get("action")).elementAt(0));
            actionNotify = getString(actionHash, "notify");
            if (actionNotify == null) {
                actionNotify = getString(actionHash, "notify-once");
            }
            destination = (String) actionHash.get("data");
            Hashtable renderHash = ((Hashtable) ((Vector) h.get("render")).elementAt(0));
            contentType = (String) renderHash.get("type");
            renderNotify = getString(renderHash, "notify");
            if (renderNotify == null) {
                renderNotify = getString(renderHash, "notify-once");
            }
            imageURL = (String) renderHash.get("data");
        }
    };
    con.setUrl(URL);
    con.setPost(false);
    con.addArgument("zoneid", getZoneId());
    con.addArgument("ua", Display.getInstance().getProperty("User-Agent", ""));
    con.addArgument("app", "1");
    con.addArgument("aid", Display.getInstance().getProperty("androidId", ""));
    con.addArgument("uuid", Display.getInstance().getProperty("uuid", ""));
    con.addArgument("im", Display.getInstance().getProperty("imei", ""));
    con.addArgument("sw", "" + Display.getInstance().getDisplayWidth());
    con.addArgument("sh", "" + Display.getInstance().getDisplayHeight());
    con.addArgument("mn", Display.getInstance().getProperty("AppName", ""));
    con.addArgument("vs3", "1");
    con.addArgument("partnerid", "1");
    con.addArgument("zc", "" + category);
    if (countryCode != null) {
        con.addArgument("cc", countryCode);
    }
    if (networkCode != null) {
        con.addArgument("nc", networkCode);
    }
    if (locale != null) {
        con.addArgument("lc", locale);
    }
    return con;
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) InputStreamReader(java.io.InputStreamReader) Hashtable(java.util.Hashtable) InputStream(java.io.InputStream) JSONParser(com.codename1.io.JSONParser) Vector(java.util.Vector) IOException(java.io.IOException)

Example 34 with URL

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

the class HTMLForm method submit.

/**
 * Called when the a form submit is needed.
 * This querys all form fields, creates a URL accordingly and sets it to the HTMLComponent
 */
void submit(String submitKey, String submitVal) {
    if (action == null) {
        return;
    }
    // If this is turned to true anywhere, the form will not be submitted
    boolean error = false;
    String url = action;
    String params = null;
    if (comps.size() > 0) {
        params = "";
        for (Enumeration e = comps.keys(); e.hasMoreElements(); ) {
            String key = (String) e.nextElement();
            Object input = comps.get(key);
            key = HTMLUtils.encodeString(key);
            String value = "";
            if (input instanceof String) {
                // hidden
                value = HTMLUtils.encodeString((String) input);
                params += key + "=" + value + "&";
            } else if (input instanceof Hashtable) {
                // checkbox / radiobutton
                Hashtable options = (Hashtable) input;
                for (Enumeration e2 = options.keys(); e2.hasMoreElements(); ) {
                    Button b = (Button) e2.nextElement();
                    if (b.isSelected()) {
                        params += key + "=" + HTMLUtils.encodeString((String) options.get(b)) + "&";
                    }
                }
            } else if (input instanceof TextArea) {
                // catches both textareas and text input fields
                TextArea tf = ((TextArea) input);
                String text = tf.getText();
                String errorMsg = null;
                if (HTMLComponent.SUPPORT_INPUT_FORMAT) {
                    boolean ok = false;
                    if (text.equals("")) {
                        // check empty - Note that emptyok/-wap-input-required overrides input format
                        if (emptyNotOk.contains(tf)) {
                            errorMsg = htmlC.getUIManager().localize("html.format.emptynotok", "Field can't be empty");
                            error = true;
                        } else if (emptyOk.contains(tf)) {
                            ok = true;
                        }
                    }
                    if ((!error) && (!ok)) {
                        // If there's already an error or it has been cleared by the emptyOK field, no need to check
                        HTMLInputFormat inputFormat = (HTMLInputFormat) inputFormats.get(tf);
                        if ((inputFormat != null) && (!inputFormat.verifyString(text))) {
                            String emptyStr = "";
                            if (emptyOk.contains(tf)) {
                                emptyStr = htmlC.getUIManager().localize("html.format.oremptyok", " or an empty string");
                            } else if (emptyNotOk.contains(tf)) {
                                emptyStr = htmlC.getUIManager().localize("html.format.andemptynotok", " and cannot be an empty string");
                            }
                            errorMsg = htmlC.getUIManager().localize("html.format.errordesc", "Malformed text. Correct value: ") + inputFormat.toString() + emptyStr;
                            error = true;
                        }
                    }
                }
                if (htmlC.getHTMLCallback() != null) {
                    int type = HTMLCallback.FIELD_TEXT;
                    if ((tf.getConstraint() & TextArea.PASSWORD) != 0) {
                        type = HTMLCallback.FIELD_PASSWORD;
                    }
                    text = htmlC.getHTMLCallback().fieldSubmitted(htmlC, tf, url, key, text, type, errorMsg);
                }
                if (errorMsg == null) {
                    params += key + "=" + HTMLUtils.encodeString(text) + "&";
                }
            } else if (input instanceof ComboBox) {
                // drop down lists (single selection)
                Object item = ((ComboBox) input).getSelectedItem();
                if (item instanceof OptionItem) {
                    value = ((OptionItem) item).getValue();
                    params += key + "=" + HTMLUtils.encodeString(value) + "&";
                }
            // if not - value may be an OPTGROUP label in an only optgroup combobox
            } else if (input instanceof MultiComboBox) {
                // drop down lists (multiple selection)
                Vector selected = ((MultiComboBox) input).getSelected();
                for (int i = 0; i < selected.size(); i++) {
                    Object item = selected.elementAt(i);
                    if (item instanceof OptionItem) {
                        value = ((OptionItem) item).getValue();
                        params += key + "=" + HTMLUtils.encodeString(value) + "&";
                    }
                // if not - value may be an OPTGROUP label in an only optgroup combobox
                }
            }
        }
        if (params.endsWith("&")) {
            // trim the extra &
            params = params.substring(0, params.length() - 1);
        }
    }
    // Add the submit button param, only if the key is non-null (unnamed submit buttons are not passed as parameters)
    if (submitKey != null) {
        if (params == null) {
            params = "";
        }
        if (!params.equals("")) {
            params = params + "&";
        }
        params = params + HTMLUtils.encodeString(submitKey) + "=" + HTMLUtils.encodeString(submitVal);
    }
    if (!error) {
        DocumentInfo docInfo = new DocumentInfo(url, params, isPostMethod);
        if ((encType != null) && (!encType.equals(""))) {
            docInfo.setEncoding(encType);
        }
        htmlC.setPage(docInfo);
    }
}
Also used : Enumeration(java.util.Enumeration) TextArea(com.codename1.ui.TextArea) Hashtable(java.util.Hashtable) ComboBox(com.codename1.ui.ComboBox) RadioButton(com.codename1.ui.RadioButton) Button(com.codename1.ui.Button) Vector(java.util.Vector)

Example 35 with URL

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

the class SetPageURLHierarchyTest method start.

public void start() {
    if (current != null) {
        current.show();
        return;
    }
    Form wform = new Form("wform", new BorderLayout());
    final BrowserComponent browser = new BrowserComponent();
    try {
        browser.setURLHierarchy("/Page.html");
    } catch (IOException ex) {
        Dialog.show("Error", "cannot set URL." + "\nError: " + ex.toString(), "OK", null);
    }
    wform.addComponent(BorderLayout.CENTER, browser);
    wform.show();
}
Also used : BorderLayout(com.codename1.ui.layouts.BorderLayout) Form(com.codename1.ui.Form) BrowserComponent(com.codename1.ui.BrowserComponent) 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