Search in sources :

Example 16 with Message

use of com.codename1.messaging.Message in project CodenameOne by codenameone.

the class Push method sendPushMessage.

/**
 * Sends a push message and returns true if server delivery succeeded, notice that the
 * push message isn't guaranteed to reach all devices.
 *
 * @param body the body of the message
 * @param deviceKey an optional parameter (can be null) when sending to a specific device
 * @param production whether pushing to production or test/sandbox environment
 * @param googleAuthKey authorization key from the google play store
 * @param iosCertificateURL a URL where you host the iOS certificate for this applications push capabilities.
 * @param iosCertificatePassword the password for the push certificate
 * @param bbUrl the URL to which the push should be submitted when sending a blackberry push for evaluation use https://pushapi.eval.blackberry.com
 * for production you will need to apply at https://cp310.pushapi.na.blackberry.com
 * @param bbApp the application id to authenticate on push for RIM devices
 * @param bbPass the application password credentials authenticate on push for RIM devices
 * @param bbPort the port of the blackberry push
 * @return true if the message reached the Codename One server successfully, this makes no guarantee
 * of delivery.
 * @deprecated this method sends a push using the old push servers which will be retired, you need to switch
 * to the equivalent method that accepts a push token
 */
public static boolean sendPushMessage(String body, String deviceKey, boolean production, String googleAuthKey, String iosCertificateURL, String iosCertificatePassword, String bbUrl, String bbApp, String bbPass, String bbPort) {
    ConnectionRequest cr = createPushMessage(body, deviceKey, production, googleAuthKey, iosCertificateURL, iosCertificatePassword, bbUrl, bbApp, bbPass, bbPort);
    NetworkManager.getInstance().addToQueueAndWait(cr);
    if (cr.getResposeCode() == 200) {
        return true;
    }
    return false;
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest)

Example 17 with Message

use of com.codename1.messaging.Message in project CodenameOne by codenameone.

the class EmailShare method share.

/**
 * {@inheritDoc}
 */
public void share(final String toShare, final String image, final String mimeType) {
    final Form currentForm = Display.getInstance().getCurrent();
    final Form contactsForm = new Form("Contacts");
    contactsForm.setLayout(new BorderLayout());
    contactsForm.setScrollable(false);
    contactsForm.addComponent(BorderLayout.CENTER, new Label("Please wait..."));
    contactsForm.show();
    Display.getInstance().startThread(new Runnable() {

        public void run() {
            String[] ids = ContactsManager.getAllContacts();
            if (ids == null || ids.length == 0) {
                Display.getInstance().callSerially(new Runnable() {

                    public void run() {
                        Dialog.show("Failed to Share", "No Contacts Found", "Ok", null);
                        currentForm.showBack();
                    }
                });
                return;
            }
            ContactsModel model = new ContactsModel(ids);
            final List contacts = new List(model);
            contacts.setRenderer(createListRenderer());
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    contacts.addActionListener(new ActionListener() {

                        public void actionPerformed(ActionEvent evt) {
                            final ShareForm[] f = new ShareForm[1];
                            Hashtable contact = (Hashtable) contacts.getSelectedItem();
                            if (image == null) {
                                f[0] = new ShareForm(contactsForm, "Send Email", (String) contact.get("email"), toShare, new ActionListener() {

                                    public void actionPerformed(ActionEvent evt) {
                                        String[] recieptents = new String[1];
                                        recieptents[0] = f[0].getTo();
                                        Message msg = new Message(toShare);
                                        Message.sendMessage(recieptents, "share", msg);
                                        finish();
                                    }
                                });
                                f[0].show();
                            } else {
                                f[0] = new ShareForm(contactsForm, "Send Email", (String) contact.get("email"), toShare, image, new ActionListener() {

                                    public void actionPerformed(ActionEvent evt) {
                                        String[] recieptents = new String[1];
                                        recieptents[0] = f[0].getTo();
                                        Message msg = new Message(toShare);
                                        msg.setAttachment(image);
                                        msg.setMimeType(mimeType);
                                        Message.sendMessage(recieptents, "share", msg);
                                        finish();
                                    }
                                });
                                f[0].show();
                            }
                        }
                    });
                    contactsForm.addComponent(BorderLayout.CENTER, contacts);
                    Command back = new Command("Back") {

                        public void actionPerformed(ActionEvent evt) {
                            currentForm.showBack();
                        }
                    };
                    contactsForm.addCommand(back);
                    contactsForm.setBackCommand(back);
                    contactsForm.revalidate();
                }
            });
        }
    }, "Email Thread").start();
}
Also used : Message(com.codename1.messaging.Message) ActionEvent(com.codename1.ui.events.ActionEvent) Hashtable(java.util.Hashtable) BorderLayout(com.codename1.ui.layouts.BorderLayout) ActionListener(com.codename1.ui.events.ActionListener) ContactsModel(com.codename1.contacts.ContactsModel)

Example 18 with Message

use of com.codename1.messaging.Message in project CodenameOne by codenameone.

the class CodenameOneImplementation method registerPollingFallback.

/**
 * Registers a polling thread to simulate push notification
 */
protected static void registerPollingFallback() {
    if (pollingThreadRunning || callback == null) {
        return;
    }
    pollingThreadRunning = true;
    final long pushId = Preferences.get("push_id", (long) -1);
    if (pushId > -1) {
        new CodenameOneThread(new Runnable() {

            public void run() {
                String lastReq = Preferences.get("last_push_req", "0");
                while (pollingThreadRunning) {
                    try {
                        ConnectionRequest cr = new ConnectionRequest();
                        cr.setUrl(Display.getInstance().getProperty("cloudServerURL", "https://codename-one.appspot.com/") + "pollManualPush");
                        cr.setPost(false);
                        cr.setFailSilently(true);
                        cr.addArgument("i", "" + pushId);
                        cr.addArgument("last", lastReq);
                        NetworkManager.getInstance().addToQueueAndWait(cr);
                        if (cr.getResponseCode() != 200) {
                            callback.pushRegistrationError("Server registration error", 1);
                        } else {
                            DataInputStream di = new DataInputStream(new ByteArrayInputStream(cr.getResponseData()));
                            if (di.readBoolean()) {
                                byte type = di.readByte();
                                String message = di.readUTF();
                                lastReq = "" + di.readLong();
                                Preferences.set("last_push_req", lastReq);
                                callback.push(message);
                            }
                        }
                    } catch (IOException ex) {
                        Log.e(ex);
                    }
                    try {
                        synchronized (callback) {
                            callback.wait(pollingMillis);
                        }
                    } catch (Throwable t) {
                        Log.e(t);
                    }
                }
            }
        }, "Polling Thread").start();
    }
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream)

Example 19 with Message

use of com.codename1.messaging.Message in project CodenameOne by codenameone.

the class ToastBar method showMessage.

/**
 * Simplifies a common use case of showing a message with an icon that fades out after a few seconds
 * @param msg the message
 * @param icon the material icon to show from {@link com.codename1.ui.FontImage}
 * @param timeout the timeout value in milliseconds
 * @param listener the action to perform when the ToastBar is tapped
 */
public static void showMessage(String msg, char icon, int timeout, ActionListener listener) {
    ToastBar.Status s = ToastBar.getInstance().createStatus();
    Style stl = UIManager.getInstance().getComponentStyle(s.getMessageUIID());
    s.setIcon(FontImage.createMaterial(icon, stl, 4));
    s.setMessage(msg);
    if (listener != null) {
        s.setListener(listener);
    }
    s.setExpires(timeout);
    s.show();
}
Also used : Style(com.codename1.ui.plaf.Style)

Example 20 with Message

use of com.codename1.messaging.Message in project CodenameOne by codenameone.

the class SEBrowserComponent method init.

private static void init(SEBrowserComponent self, BrowserComponent p) {
    final WeakReference<SEBrowserComponent> weakSelf = new WeakReference<>(self);
    final WeakReference<BrowserComponent> weakP = new WeakReference<>(p);
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            SEBrowserComponent self = weakSelf.get();
            if (self == null) {
                return;
            }
            self.cnt = new InternalJPanel(self.instance, self);
            // <--- Important if container is opaque it will cause
            self.cnt.setOpaque(false);
            // all kinds of flicker due to painting conflicts with CN1 pipeline.
            self.cnt.setLayout(new BorderLayout());
            self.cnt.add(BorderLayout.CENTER, self.panel);
        // cnt.setVisible(false);
        }
    });
    self.web.getEngine().getLoadWorker().messageProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> ov, String t, String t1) {
            SEBrowserComponent self = weakSelf.get();
            BrowserComponent p = weakP.get();
            if (self == null || p == null) {
                return;
            }
            if (t1.startsWith("Loading http:") || t1.startsWith("Loading file:") || t1.startsWith("Loading https:")) {
                String url = t1.substring("Loading ".length());
                if (!url.equals(self.currentURL)) {
                    p.fireWebEvent("onStart", new ActionEvent(url));
                }
                self.currentURL = url;
            } else if ("Loading complete".equals(t1)) {
            }
        }
    });
    self.web.getEngine().setOnAlert(new EventHandler<WebEvent<String>>() {

        @Override
        public void handle(WebEvent<String> t) {
            BrowserComponent p = weakP.get();
            if (p == null) {
                return;
            }
            String msg = t.getData();
            if (msg.startsWith("!cn1_message:")) {
                System.out.println("Receiving message " + msg);
                p.fireWebEvent("onMessage", new ActionEvent(msg.substring("!cn1_message:".length())));
            }
        }
    });
    self.web.getEngine().getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {

        @Override
        public void changed(ObservableValue<? extends Throwable> ov, Throwable t, Throwable t1) {
            System.out.println("Received exception: " + t1.getMessage());
            if (ov.getValue() != null) {
                ov.getValue().printStackTrace();
            }
            if (t != ov.getValue() && t != null) {
                t.printStackTrace();
            }
            if (t1 != ov.getValue() && t1 != t && t1 != null) {
                t.printStackTrace();
            }
        }
    });
    self.web.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {

        @Override
        public void changed(ObservableValue ov, State oldState, State newState) {
            SEBrowserComponent self = weakSelf.get();
            BrowserComponent p = weakP.get();
            try {
                netscape.javascript.JSObject w = (netscape.javascript.JSObject) self.web.getEngine().executeScript("window");
                if (w == null) {
                    System.err.println("Could not get window");
                } else {
                    Bridge b = new Bridge(p);
                    self.putClientProperty("SEBrowserComponent.Bridge.jconsole", b);
                    w.setMember("jconsole", b);
                }
            } catch (Throwable t) {
                Log.e(t);
            }
            if (self == null || p == null) {
                return;
            }
            String url = self.web.getEngine().getLocation();
            if (newState == State.SCHEDULED) {
                p.fireWebEvent("onStart", new ActionEvent(url));
            } else if (newState == State.RUNNING) {
                p.fireWebEvent("onLoadResource", new ActionEvent(url));
            } else if (newState == State.SUCCEEDED) {
                if (!p.isNativeScrollingEnabled()) {
                    self.web.getEngine().executeScript("document.body.style.overflow='hidden'");
                }
                // let's just add a client property to the BrowserComponent to enable firebug
                if (Boolean.TRUE.equals(p.getClientProperty("BrowserComponent.firebug"))) {
                    self.web.getEngine().executeScript("if (!document.getElementById('FirebugLite')){E = document['createElement' + 'NS'] && document.documentElement.namespaceURI;E = E ? document['createElement' + 'NS'](E, 'script') : document['createElement']('script');E['setAttribute']('id', 'FirebugLite');E['setAttribute']('src', 'https://getfirebug.com/' + 'firebug-lite.js' + '#startOpened');E['setAttribute']('FirebugLite', '4');(document['getElementsByTagName']('head')[0] || document['getElementsByTagName']('body')[0]).appendChild(E);E = new Image;E['setAttribute']('src', 'https://getfirebug.com/' + '#startOpened');}");
                }
                netscape.javascript.JSObject window = (netscape.javascript.JSObject) self.web.getEngine().executeScript("window");
                Bridge b = new Bridge(p);
                self.putClientProperty("SEBrowserComponent.Bridge.cn1application", b);
                window.setMember("cn1application", b);
                self.web.getEngine().executeScript("while (window._cn1ready && window._cn1ready.length > 0) {var f = window._cn1ready.shift(); f();}");
                // System.out.println("cn1application is "+self.web.getEngine().executeScript("window.cn1application && window.cn1application.shouldNavigate"));
                self.web.getEngine().executeScript("window.addEventListener('unload', function(e){console.log('unloading...');return 'foobar';});");
                p.fireWebEvent("onLoad", new ActionEvent(url));
            }
            self.currentURL = url;
            self.repaint();
        }
    });
    self.web.getEngine().getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {

        @Override
        public void changed(ObservableValue<? extends Throwable> ov, Throwable t, Throwable t1) {
            BrowserComponent p = weakP.get();
            if (p == null) {
                return;
            }
            t1.printStackTrace();
            if (t1 == null) {
                if (t == null) {
                    p.fireWebEvent("onError", new ActionEvent("Unknown error", -1));
                } else {
                    p.fireWebEvent("onError", new ActionEvent(t.getMessage(), -1));
                }
            } else {
                p.fireWebEvent("onError", new ActionEvent(t1.getMessage(), -1));
            }
        }
    });
    // Monitor the location property so that we can send the shouldLoadURL event.
    // This allows us to cancel the loading of a URL if we want to handle it ourself.
    self.web.getEngine().locationProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> prop, String before, String after) {
            SEBrowserComponent self = weakSelf.get();
            BrowserComponent p = weakP.get();
            if (self == null || p == null) {
                return;
            }
            if (!p.fireBrowserNavigationCallbacks(self.web.getEngine().getLocation())) {
                self.web.getEngine().getLoadWorker().cancel();
            }
        }
    });
    self.adjustmentListener = new AdjustmentListener() {

        @Override
        public void adjustmentValueChanged(AdjustmentEvent e) {
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    SEBrowserComponent self = weakSelf.get();
                    if (self == null) {
                        return;
                    }
                    self.onPositionSizeChange();
                }
            });
        }
    };
}
Also used : ActionEvent(com.codename1.ui.events.ActionEvent) ObservableValue(javafx.beans.value.ObservableValue) BorderLayout(java.awt.BorderLayout) WeakReference(java.lang.ref.WeakReference) WebEvent(javafx.scene.web.WebEvent) AdjustmentEvent(java.awt.event.AdjustmentEvent) State(javafx.concurrent.Worker.State) AdjustmentListener(java.awt.event.AdjustmentListener)

Aggregations

ConnectionRequest (com.codename1.io.ConnectionRequest)8 ActionListener (com.codename1.ui.events.ActionListener)6 IOException (java.io.IOException)5 Message (au.com.dius.pact.model.v3.messaging.Message)4 ActionEvent (com.codename1.ui.events.ActionEvent)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 InputStream (java.io.InputStream)3 MessagePact (au.com.dius.pact.model.v3.messaging.MessagePact)2 BufferedInputStream (com.codename1.io.BufferedInputStream)2 NetworkEvent (com.codename1.io.NetworkEvent)2 Message (com.codename1.messaging.Message)2 Dialog (com.codename1.ui.Dialog)2 BorderLayout (com.codename1.ui.layouts.BorderLayout)2 DataInputStream (java.io.DataInputStream)2 Method (java.lang.reflect.Method)2 Hashtable (java.util.Hashtable)2 Vector (java.util.Vector)2 ActivityNotFoundException (android.content.ActivityNotFoundException)1 Intent (android.content.Intent)1 Uri (android.net.Uri)1