Search in sources :

Example 21 with Message

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

the class JavaSEPort method createSkinsMenu.

private JMenu createSkinsMenu(final JFrame frm, final JMenu menu) throws MalformedURLException {
    JMenu m;
    if (menu == null) {
        m = new JMenu("Skins");
        m.setDoubleBuffered(true);
    } else {
        m = menu;
        m.removeAll();
    }
    final JMenu skinMenu = m;
    Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
    String skinNames = pref.get("skins", DEFAULT_SKINS);
    if (skinNames != null) {
        if (skinNames.length() < DEFAULT_SKINS.length()) {
            skinNames = DEFAULT_SKINS;
        }
        ButtonGroup skinGroup = new ButtonGroup();
        StringTokenizer tkn = new StringTokenizer(skinNames, ";");
        while (tkn.hasMoreTokens()) {
            final String current = tkn.nextToken();
            String name = current;
            if (current.contains(":")) {
                try {
                    URL u = new URL(current);
                    File f = new File(u.getFile());
                    if (!f.exists()) {
                        continue;
                    }
                    name = f.getName();
                } catch (Exception e) {
                    continue;
                }
            } else {
                // remove the old builtin skins from the menu
                if (current.startsWith("/") && !current.equals("/iphone3gs.skin")) {
                    continue;
                }
            }
            String d = System.getProperty("dskin");
            JRadioButtonMenuItem i = new JRadioButtonMenuItem(name, name.equals(pref.get("skin", d)));
            i.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent ae) {
                    if (netMonitor != null) {
                        netMonitor.dispose();
                        netMonitor = null;
                    }
                    if (perfMonitor != null) {
                        perfMonitor.dispose();
                        perfMonitor = null;
                    }
                    Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                    pref.putBoolean("desktopSkin", false);
                    String mainClass = System.getProperty("MainClass");
                    if (mainClass != null) {
                        pref.put("skin", current);
                        deinitializeSync();
                        frm.dispose();
                        System.setProperty("reload.simulator", "true");
                    } else {
                        loadSkinFile(current, frm);
                        refreshSkin(frm);
                    }
                }
            });
            skinGroup.add(i);
            skinMenu.add(i);
        }
    }
    JMenuItem dSkin = new JMenuItem("Desktop.skin");
    dSkin.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            if (netMonitor != null) {
                netMonitor.dispose();
                netMonitor = null;
            }
            if (perfMonitor != null) {
                perfMonitor.dispose();
                perfMonitor = null;
            }
            Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
            pref.putBoolean("desktopSkin", true);
            String mainClass = System.getProperty("MainClass");
            if (mainClass != null) {
                deinitializeSync();
                frm.dispose();
                System.setProperty("reload.simulator", "true");
            }
        }
    });
    skinMenu.addSeparator();
    skinMenu.add(dSkin);
    skinMenu.addSeparator();
    JMenuItem more = new JMenuItem("More...");
    skinMenu.add(more);
    more.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final JDialog pleaseWait = new JDialog(frm, false);
            pleaseWait.setLocationRelativeTo(frm);
            pleaseWait.setTitle("Message");
            pleaseWait.setLayout(new BorderLayout());
            pleaseWait.add(new JLabel("  Please Wait...  "), BorderLayout.CENTER);
            pleaseWait.pack();
            pleaseWait.setVisible(true);
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    final JDialog d = new JDialog(frm, true);
                    d.setLocationRelativeTo(frm);
                    d.setTitle("Skins");
                    d.setLayout(new BorderLayout());
                    String userDir = System.getProperty("user.home");
                    final File skinDir = new File(userDir + "/.codenameone/");
                    if (!skinDir.exists()) {
                        skinDir.mkdir();
                    }
                    Vector data = new Vector();
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    final Document[] doc = new Document[1];
                    try {
                        DocumentBuilder db = dbf.newDocumentBuilder();
                        Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                        InputStream is = openSkinsURL();
                        doc[0] = db.parse(is);
                        NodeList skins = doc[0].getElementsByTagName("Skin");
                        for (int i = 0; i < skins.getLength(); i++) {
                            Node skin = skins.item(i);
                            NamedNodeMap attr = skin.getAttributes();
                            String url = attr.getNamedItem("url").getNodeValue();
                            int ver = 0;
                            Node n = attr.getNamedItem("version");
                            if (n != null) {
                                ver = Integer.parseInt(n.getNodeValue());
                            }
                            boolean exists = new File(skinDir.getAbsolutePath() + url).exists();
                            if (!(exists) || Integer.parseInt(pref.get(url, "0")) < ver) {
                                Vector row = new Vector();
                                row.add(new Boolean(false));
                                row.add(new ImageIcon(new URL(defaultCodenameOneComProtocol + "://www.codenameone.com/OTA" + attr.getNamedItem("icon").getNodeValue())));
                                row.add(attr.getNamedItem("name").getNodeValue());
                                if (exists) {
                                    row.add("Update");
                                } else {
                                    row.add("New");
                                }
                                data.add(row);
                            }
                        }
                    } catch (Exception ex) {
                        Logger.getLogger(JavaSEPort.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    if (data.size() == 0) {
                        pleaseWait.setVisible(false);
                        JOptionPane.showMessageDialog(frm, "No New Skins to Install");
                        return;
                    }
                    Vector cols = new Vector();
                    cols.add("Install");
                    cols.add("Icon");
                    cols.add("Name");
                    cols.add("");
                    final DefaultTableModel tableModel = new DefaultTableModel(data, cols) {

                        @Override
                        public boolean isCellEditable(int row, int column) {
                            return column == 0;
                        }
                    };
                    JTable skinsTable = new JTable(tableModel) {

                        @Override
                        public Class<?> getColumnClass(int column) {
                            if (column == 0) {
                                return Boolean.class;
                            }
                            if (column == 1) {
                                return Icon.class;
                            }
                            return super.getColumnClass(column);
                        }
                    };
                    skinsTable.setRowHeight(112);
                    skinsTable.getTableHeader().setReorderingAllowed(false);
                    d.add(new JScrollPane(skinsTable), BorderLayout.CENTER);
                    JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
                    JButton download = new JButton("Download");
                    download.addActionListener(new ActionListener() {

                        @Override
                        public void actionPerformed(ActionEvent e) {
                            final Vector toDowload = new Vector();
                            NodeList skins = doc[0].getElementsByTagName("Skin");
                            for (int i = 0; i < tableModel.getRowCount(); i++) {
                                if (((Boolean) tableModel.getValueAt(i, 0)).booleanValue()) {
                                    Node skin;
                                    for (int j = 0; j < skins.getLength(); j++) {
                                        skin = skins.item(j);
                                        NamedNodeMap attr = skin.getAttributes();
                                        if (attr.getNamedItem("name").getNodeValue().equals(tableModel.getValueAt(i, 2))) {
                                            String url = attr.getNamedItem("url").getNodeValue();
                                            String[] data = new String[2];
                                            data[0] = defaultCodenameOneComProtocol + "://www.codenameone.com/OTA" + url;
                                            data[1] = attr.getNamedItem("version").getNodeValue();
                                            toDowload.add(data);
                                            break;
                                        }
                                    }
                                }
                            }
                            if (toDowload.size() > 0) {
                                final JDialog downloadMessage = new JDialog(d, true);
                                downloadMessage.setTitle("Downloading");
                                downloadMessage.setLayout(new FlowLayout());
                                downloadMessage.setLocationRelativeTo(d);
                                final JLabel details = new JLabel("<br><br>Details");
                                downloadMessage.add(details);
                                final JLabel progress = new JLabel("Progress<br><br>");
                                downloadMessage.add(progress);
                                new Thread() {

                                    @Override
                                    public void run() {
                                        for (Iterator it = toDowload.iterator(); it.hasNext(); ) {
                                            String[] data = (String[]) it.next();
                                            String url = data[0];
                                            details.setText(url.substring(url.lastIndexOf("/")));
                                            details.repaint();
                                            progress.setText("");
                                            progress.repaint();
                                            try {
                                                File skin = downloadSkin(skinDir, url, data[1], progress);
                                                if (skin.exists()) {
                                                    addSkinName(skin.toURI().toString());
                                                }
                                            } catch (Exception e) {
                                            }
                                        }
                                        downloadMessage.setVisible(false);
                                        d.setVisible(false);
                                        try {
                                            createSkinsMenu(frm, skinMenu);
                                        } catch (MalformedURLException ex) {
                                            Logger.getLogger(JavaSEPort.class.getName()).log(Level.SEVERE, null, ex);
                                        }
                                    }
                                }.start();
                                downloadMessage.pack();
                                downloadMessage.setSize(200, 70);
                                downloadMessage.setVisible(true);
                            } else {
                                JOptionPane.showMessageDialog(d, "Choose a Skin to Download");
                            }
                        }
                    });
                    p.add(download);
                    d.add(p, BorderLayout.SOUTH);
                    d.pack();
                    pleaseWait.dispose();
                    d.setVisible(true);
                }
            });
        }
    });
    skinMenu.addSeparator();
    JMenuItem addSkin = new JMenuItem("Add New...");
    skinMenu.add(addSkin);
    addSkin.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            FileDialog picker = new FileDialog(frm, "Add Skin");
            picker.setMode(FileDialog.LOAD);
            picker.setFilenameFilter(new FilenameFilter() {

                public boolean accept(File file, String string) {
                    return string.endsWith(".skin");
                }
            });
            picker.setModal(true);
            picker.setVisible(true);
            String file = picker.getFile();
            if (file != null) {
                if (netMonitor != null) {
                    netMonitor.dispose();
                    netMonitor = null;
                }
                if (perfMonitor != null) {
                    perfMonitor.dispose();
                    perfMonitor = null;
                }
                String mainClass = System.getProperty("MainClass");
                if (mainClass != null) {
                    Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                    pref.put("skin", picker.getDirectory() + File.separator + file);
                    deinitializeSync();
                    frm.dispose();
                    System.setProperty("reload.simulator", "true");
                } else {
                    loadSkinFile(picker.getDirectory() + File.separator + file, frm);
                    refreshSkin(frm);
                }
            }
        }
    });
    skinMenu.addSeparator();
    JMenuItem reset = new JMenuItem("Reset Skins");
    skinMenu.add(reset);
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            if (JOptionPane.showConfirmDialog(frm, "Are you sure you want to reset skins to default?", "Clean Storage", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
                Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                pref.put("skins", DEFAULT_SKINS);
                String userDir = System.getProperty("user.home");
                final File skinDir = new File(userDir + "/.codenameone/");
                if (skinDir.exists()) {
                    File[] childs = skinDir.listFiles();
                    for (int i = 0; i < childs.length; i++) {
                        File child = childs[i];
                        if (child.getName().endsWith(".skin")) {
                            child.delete();
                        }
                    }
                }
                if (netMonitor != null) {
                    netMonitor.dispose();
                    netMonitor = null;
                }
                if (perfMonitor != null) {
                    perfMonitor.dispose();
                    perfMonitor = null;
                }
                String mainClass = System.getProperty("MainClass");
                if (mainClass != null) {
                    pref.put("skin", "/iphone3gs.skin");
                    deinitializeSync();
                    frm.dispose();
                    System.setProperty("reload.simulator", "true");
                } else {
                    loadSkinFile("/iphone3gs.skin", frm);
                    refreshSkin(frm);
                }
            }
        }
    });
    return skinMenu;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) ActionEvent(java.awt.event.ActionEvent) Node(org.w3c.dom.Node) DefaultTableModel(javax.swing.table.DefaultTableModel) Document(org.w3c.dom.Document) FilenameFilter(java.io.FilenameFilter) PathIterator(java.awt.geom.PathIterator) Preferences(java.util.prefs.Preferences) Vector(java.util.Vector) NamedNodeMap(org.w3c.dom.NamedNodeMap) BufferedInputStream(com.codename1.io.BufferedInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipInputStream(java.util.zip.ZipInputStream) NodeList(org.w3c.dom.NodeList) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) EOFException(java.io.EOFException) FontFormatException(java.awt.FontFormatException) Point(java.awt.Point) StringTokenizer(java.util.StringTokenizer) ActionListener(java.awt.event.ActionListener) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileDialog(java.awt.FileDialog)

Example 22 with Message

use of com.codename1.messaging.Message 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 23 with Message

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

the class FacebookShare method share.

/**
 * {@inheritDoc}
 */
public void share(String text, final String image, final String mime) {
    final ShareForm[] f = new ShareForm[1];
    if (image == null) {
        f[0] = new ShareForm(getOriginal(), "Post on My Wall", null, text, new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                try {
                    InfiniteProgress inf = new InfiniteProgress();
                    final Dialog progress = inf.showInifiniteBlocking();
                    FaceBookAccess.getInstance().addResponseCodeListener(new ActionListener() {

                        public void actionPerformed(ActionEvent evt) {
                            NetworkEvent ne = (NetworkEvent) evt;
                            int code = ne.getResponseCode();
                            FaceBookAccess.getInstance().removeResponseCodeListener(this);
                            progress.dispose();
                            Dialog.show("Failed to Share", "for some reason sharing has failed, try again later.", "Ok", null);
                            finish();
                        }
                    });
                    FaceBookAccess.getInstance().postOnWall("me", f[0].getMessage(), new ActionListener() {

                        public void actionPerformed(ActionEvent evt) {
                            progress.dispose();
                            finish();
                        }
                    });
                } catch (IOException ex) {
                    Log.e(ex);
                    System.out.println("failed to share " + ex.getMessage());
                }
            }
        });
        f[0].show();
    } else {
        f[0] = new ShareForm(getOriginal(), "Post on My Wall", null, text, image, new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                InfiniteProgress inf = new InfiniteProgress();
                final Dialog progress = inf.showInifiniteBlocking();
                FaceBookAccess.getInstance().addResponseCodeListener(new ActionListener() {

                    public void actionPerformed(ActionEvent evt) {
                        NetworkEvent ne = (NetworkEvent) evt;
                        int code = ne.getResponseCode();
                        FaceBookAccess.getInstance().removeResponseCodeListener(this);
                        progress.dispose();
                        Dialog.show("Failed to Share", "for some reason sharing has failed, try again later.", "Ok", null);
                        finish();
                    }
                });
                MultipartRequest req = new MultipartRequest();
                req.addResponseListener(new ActionListener() {

                    public void actionPerformed(ActionEvent evt) {
                        progress.dispose();
                        finish();
                    }
                });
                final String endpoint = "https://graph.facebook.com/me/photos?access_token=" + token;
                req.setUrl(endpoint);
                req.addArgumentNoEncoding("message", f[0].getMessage());
                InputStream is = null;
                try {
                    is = FileSystemStorage.getInstance().openInputStream(image);
                    req.addData("source", is, FileSystemStorage.getInstance().getLength(image), mime);
                    NetworkManager.getInstance().addToQueue(req);
                } catch (IOException ioe) {
                    Log.e(ioe);
                }
            }
        });
        f[0].show();
    }
}
Also used : ActionListener(com.codename1.ui.events.ActionListener) InfiniteProgress(com.codename1.components.InfiniteProgress) ActionEvent(com.codename1.ui.events.ActionEvent) Dialog(com.codename1.ui.Dialog) InputStream(java.io.InputStream) NetworkEvent(com.codename1.io.NetworkEvent) IOException(java.io.IOException) MultipartRequest(com.codename1.io.MultipartRequest)

Example 24 with Message

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

the class ComponentTest method start.

public void start() {
    if (current != null) {
        current.show();
        return;
    }
    Form hi = new Form("Hi World", BoxLayout.y());
    hi.add(new Label("Hi World"));
    hi.show();
    if (System.currentTimeMillis() < 100) {
        QRScanner.scanQRCode(new ScanResult() {

            public void scanCompleted(String contents, String formatName, byte[] rawBytes) {
                Dialog.show("Completed", contents, "OK", null);
            }

            public void scanCanceled() {
                Dialog.show("Cancelled", "Scan Cancelled", "OK", null);
            }

            public void scanError(int errorCode, String message) {
                Dialog.show("Error", message, "OK", null);
            }
        });
    }
}
Also used : ScanResult(com.codename1.ext.codescan.ScanResult) Form(com.codename1.ui.Form) Label(com.codename1.ui.Label)

Example 25 with Message

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

the class TestComponent method testCookies.

private void testCookies() throws IOException {
    Cookie.clearCookiesFromStorage();
    String baseUrl = "http://solutions.weblite.ca/cn1tests/cookie";
    String clearCookiesUrl = baseUrl + "/reset.php";
    String setCookiesUrl = baseUrl + "/set.php";
    String checkCookiesUrl = baseUrl + "/check.php";
    String setCookiesUrlSession = baseUrl + "/set_session.php";
    // Try without native cookie store
    ConnectionRequest.setUseNativeCookieStore(false);
    ConnectionRequest.fetchJSON(clearCookiesUrl);
    Map<String, Object> res = ConnectionRequest.fetchJSON(checkCookiesUrl);
    System.out.println(res);
    TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
    ConnectionRequest.fetchJSON(setCookiesUrl);
    res = ConnectionRequest.fetchJSON(checkCookiesUrl);
    TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
    // Now check that session cookies (no explicit expiry) are set correctly
    ConnectionRequest.fetchJSON(clearCookiesUrl);
    res = ConnectionRequest.fetchJSON(checkCookiesUrl);
    TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
    ConnectionRequest.fetchJSON(setCookiesUrlSession);
    res = ConnectionRequest.fetchJSON(checkCookiesUrl);
    TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
    // Try with native cookie store
    ConnectionRequest.setUseNativeCookieStore(true);
    ConnectionRequest.fetchJSON(clearCookiesUrl);
    res = ConnectionRequest.fetchJSON(checkCookiesUrl);
    TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
    ConnectionRequest.fetchJSON(setCookiesUrl);
    res = ConnectionRequest.fetchJSON(checkCookiesUrl);
    TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
    // Now check that session cookies (no explicit expiry) are set correctly
    ConnectionRequest.fetchJSON(clearCookiesUrl);
    res = ConnectionRequest.fetchJSON(checkCookiesUrl);
    TestUtils.assertBool(null == res.get("cookieval"), "Cookie should be null after clearing cookies but was " + res.get("cookieval"));
    ConnectionRequest.fetchJSON(setCookiesUrlSession);
    res = ConnectionRequest.fetchJSON(checkCookiesUrl);
    TestUtils.assertEqual("hello", res.get("cookieval"), "Cookie set to incorrect value.");
    Throwable[] t = new Throwable[1];
    // Now test a different cookie date format.
    ConnectionRequest req = new ConnectionRequest() {

        @Override
        protected void handleException(Exception err) {
            Log.p("handling exception " + err);
            t[0] = err;
        }

        @Override
        protected void handleRuntimeException(RuntimeException err) {
            Log.p("handling runtime exception " + err);
            t[0] = err;
        }

        @Override
        protected void handleErrorResponseCode(int code, String message) {
            Log.p("Error response " + code + ", " + message);
        }
    };
    String oldProp = (String) Display.getInstance().getProperty("com.codename1.io.ConnectionRequest.throwExceptionOnFailedCookieParse", null);
    Display.getInstance().setProperty("com.codename1.io.ConnectionRequest.throwExceptionOnFailedCookieParse", "true");
    req.setUrl(baseUrl + "/test_rfc822cookie.php");
    req.setFollowRedirects(true);
    req.setPost(false);
    req.setDuplicateSupported(true);
    // req.setFailSilently(true);
    try {
        NetworkManager.getInstance().addToQueueAndWait(req);
    } finally {
        // NetworkManager.getInstance().removeErrorListener(errorListener);
        Display.getInstance().setProperty("com.codename1.io.ConnectionRequest.throwExceptionOnFailedCookieParse", oldProp);
    }
    TestUtils.assertTrue(req.getResponseCode() == 200, "Unexpected response code.  Expected 200 but found " + req.getResponseCode());
    TestUtils.assertTrue(t[0] == null, t[0] != null ? ("Exception was thrown getting URL " + t[0].getMessage()) : "");
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) IOException(java.io.IOException)

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