Search in sources :

Example 1 with DocumentInfo

use of com.codename1.ui.html.DocumentInfo 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 2 with DocumentInfo

use of com.codename1.ui.html.DocumentInfo in project CodenameOne by codenameone.

the class Ads method setAd.

/**
 * HTML ad received from the server
 * @param ad the ad to set
 */
public void setAd(String ad) {
    HTMLComponent html = new HTMLComponent(new AsyncDocumentRequestHandlerImpl() {

        protected ConnectionRequest createConnectionRequest(DocumentInfo docInfo, IOCallback callback, Object[] response) {
            ConnectionRequest req = super.createConnectionRequest(docInfo, callback, response);
            req.setFailSilently(true);
            req.addResponseCodeListener(new ActionListener() {

                public void actionPerformed(ActionEvent evt) {
                // do nothing, just make sure the html won't throw an error
                }
            });
            return req;
        }
    });
    html.setSupressExceptions(true);
    html.setHTMLCallback(this);
    html.setBodyText("<html><body><div align='center'>" + ad + "</div></body></html>");
    replace(getComponentAt(0), html, null);
    revalidate();
    html.setPageUIID("Container");
    html.getStyle().setBgTransparency(0);
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) ActionListener(com.codename1.ui.events.ActionListener) ActionEvent(com.codename1.ui.events.ActionEvent) AsyncDocumentRequestHandlerImpl(com.codename1.ui.html.AsyncDocumentRequestHandlerImpl) IOCallback(com.codename1.ui.html.IOCallback) HTMLComponent(com.codename1.ui.html.HTMLComponent) DocumentInfo(com.codename1.ui.html.DocumentInfo)

Example 3 with DocumentInfo

use of com.codename1.ui.html.DocumentInfo 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 4 with DocumentInfo

use of com.codename1.ui.html.DocumentInfo 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)

Example 5 with DocumentInfo

use of com.codename1.ui.html.DocumentInfo in project CodenameOne by codenameone.

the class AsyncDocumentRequestHandlerImpl method createConnectionRequest.

protected ConnectionRequest createConnectionRequest(final DocumentInfo docInfo, final IOCallback callback, final Object[] response) {
    return new ConnectionRequest() {

        protected void buildRequestBody(OutputStream os) throws IOException {
            if (isPost()) {
                if (docInfo.getParams() != null) {
                    OutputStreamWriter w = new OutputStreamWriter(os, docInfo.getEncoding());
                    w.write(docInfo.getParams());
                }
            }
        }

        protected void handleIOException(IOException err) {
            if (callback == null) {
                response[0] = err;
            }
            super.handleIOException(err);
        }

        protected boolean shouldAutoCloseResponse() {
            return callback != null;
        }

        protected void readResponse(InputStream input) throws IOException {
            if (callback != null) {
                callback.streamReady(input, docInfo);
            } else {
                response[0] = input;
                synchronized (LOCK) {
                    LOCK.notify();
                }
            }
        }
    };
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException)

Aggregations

ConnectionRequest (com.codename1.io.ConnectionRequest)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 Button (com.codename1.ui.Button)1 ComboBox (com.codename1.ui.ComboBox)1 EncodedImage (com.codename1.ui.EncodedImage)1 Image (com.codename1.ui.Image)1 RadioButton (com.codename1.ui.RadioButton)1 TextArea (com.codename1.ui.TextArea)1 ActionEvent (com.codename1.ui.events.ActionEvent)1 ActionListener (com.codename1.ui.events.ActionListener)1 AsyncDocumentRequestHandlerImpl (com.codename1.ui.html.AsyncDocumentRequestHandlerImpl)1 DocumentInfo (com.codename1.ui.html.DocumentInfo)1 HTMLComponent (com.codename1.ui.html.HTMLComponent)1 IOCallback (com.codename1.ui.html.IOCallback)1 Resources (com.codename1.ui.util.Resources)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 OutputStream (java.io.OutputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 Enumeration (java.util.Enumeration)1