Search in sources :

Example 36 with URL

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

the class JavaFXLoader method getJavaFXJars.

public URL[] getJavaFXJars() throws IOException {
    if (!javafxDir.exists()) {
        downloadJavaFX();
    }
    if (!javafxDir.exists()) {
        throw new RuntimeException("Failed to download JavaFX");
    }
    File javafxLibDir = new File(javafxDir, "lib");
    if (!javafxLibDir.exists()) {
        throw new RuntimeException("JavaFX is missing.  This application requires a JDK with JavaFX.");
    }
    File jarsDir = javafxLibDir;
    if ("8".equals(getJavaFXVersionStr())) {
        // JavaFX 8 jar files are in the lib/ext directory
        jarsDir = new File(javafxLibDir, "ext");
    }
    java.util.List<java.net.URL> javafxUrls = new ArrayList<java.net.URL>();
    for (File f : jarsDir.listFiles()) {
        if (!f.getName().endsWith(".jar")) {
            continue;
        }
        try {
            java.net.URL u = f.toURI().toURL();
            javafxUrls.add(u);
        } catch (Exception ex2) {
            ex2.printStackTrace();
        }
    }
    if (javafxUrls.isEmpty()) {
        throw new RuntimeException("JavaFX is missing.  This application requires a JDK with JavaFX.");
    }
    try {
        // Necessary for loading native libs
        javafxUrls.add(javafxLibDir.toURI().toURL());
    } catch (MalformedURLException mex) {
        throw new RuntimeException(mex);
    }
    return javafxUrls.toArray(new java.net.URL[javafxUrls.size()]);
}
Also used : MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) ArrayList(java.util.ArrayList) File(java.io.File) URL(java.net.URL) JavaFXNotLoadedException(com.codename1.impl.javase.fx.JavaFXLoader.JavaFXNotLoadedException) URISyntaxException(java.net.URISyntaxException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 37 with URL

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

the class SEBrowserComponent method init.

private static void init(SEBrowserComponent self, BrowserComponent p) {
    final WeakReference<SEBrowserComponent> weakSelf = new WeakReference<SEBrowserComponent>(self);
    final WeakReference<BrowserComponent> weakP = new WeakReference<BrowserComponent>(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;
            }
            /*
                // DISABLING TRANSPARENCY BECAUSE IT CAUSES A MESS WHEN SCROLLING
                // ORIGINALLY TRIED TO ADD THIS FOR CSS GENERATION, BUT LATER OPTED
                // TO ONLY USE CEF FOR THAT ANYWAYS
                // SINCE THIS FX COMPONENT IS DEPRECATED, WE'LL JUST LET IT DIE
                self.transparent = p.getStyle().getBgTransparency() == 0;
                if (self.transparent) {
                    try {
                        Class WebPage = Class.forName("com.sun.webkit.WebPage", true, SEBrowserComponent.class.getClassLoader());
                        Class Accessor = Class.forName("com.sun.javafx.webkit.Accessor", true, SEBrowserComponent.class.getClassLoader());
                        Method getPageFor = Accessor.getMethod("getPageFor", new Class[]{WebEngine.class});
                        Object webPage = getPageFor.invoke(null, self.web.getEngine());
                        Method setBackgroundColor = WebPage.getMethod("setBackgroundColor", new Class[]{int.class});
                        setBackgroundColor.invoke(webPage, 0);
                    } catch (Exception ex){}
                }
                */
            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) IBrowserComponent(com.codename1.impl.javase.IBrowserComponent) State(javafx.concurrent.Worker.State) AdjustmentListener(java.awt.event.AdjustmentListener)

Example 38 with URL

use of com.codename1.io.URL 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 39 with URL

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

the class AndroidImplementation method createIntentForURL.

private Intent createIntentForURL(String url) {
    Intent intent;
    Uri uri;
    try {
        if (url.startsWith("intent")) {
            intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
        } else {
            if (url.startsWith("/") || url.startsWith("file:")) {
                if (!checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, "This is required to open the file")) {
                    return null;
                }
            }
            intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            if (url.startsWith("/")) {
                File f = new File(url);
                Uri furi = null;
                try {
                    furi = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", f);
                } catch (Exception ex) {
                    f = makeTempCacheCopy(f);
                    furi = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", f);
                }
                if (Build.VERSION.SDK_INT < 21) {
                    List<ResolveInfo> resInfoList = getContext().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                    for (ResolveInfo resolveInfo : resInfoList) {
                        String packageName = resolveInfo.activityInfo.packageName;
                        getContext().grantUriPermission(packageName, furi, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                }
                uri = furi;
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                if (url.startsWith("file:")) {
                    File f = new File(removeFilePrefix(url));
                    System.out.println("File size: " + f.length());
                    Uri furi = null;
                    try {
                        furi = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", f);
                    } catch (Exception ex) {
                        f = makeTempCacheCopy(f);
                        furi = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", f);
                    }
                    if (Build.VERSION.SDK_INT < 21) {
                        List<ResolveInfo> resInfoList = getContext().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                        for (ResolveInfo resolveInfo : resInfoList) {
                            String packageName = resolveInfo.activityInfo.packageName;
                            getContext().grantUriPermission(packageName, furi, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        }
                    }
                    uri = furi;
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    uri = Uri.parse(url);
                }
            }
            String mimeType = getMimeType(url);
            if (mimeType != null) {
                intent.setDataAndType(uri, mimeType);
            } else {
                intent.setData(uri);
            }
        }
        return intent;
    } catch (Exception err) {
        com.codename1.io.Log.e(err);
        return null;
    }
}
Also used : Uri(android.net.Uri) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MediaException(com.codename1.media.AsyncMedia.MediaException) ParseException(java.text.ParseException) SAXException(org.xml.sax.SAXException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 40 with URL

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

the class AndroidImplementation method getAppArg.

@Override
public String getAppArg() {
    if (super.getAppArg() != null) {
        // behaviour the existed when AppArg was just another Display property.
        return super.getAppArg();
    }
    if (getActivity() == null) {
        return null;
    }
    android.content.Intent intent = getActivity().getIntent();
    if (intent != null) {
        String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
        intent.removeExtra(Intent.EXTRA_TEXT);
        Uri u = intent.getData();
        String scheme = intent.getScheme();
        if (u == null && intent.getExtras() != null) {
            if (intent.getExtras().keySet().contains("android.intent.extra.STREAM")) {
                try {
                    u = (Uri) intent.getParcelableExtra("android.intent.extra.STREAM");
                    scheme = u.getScheme();
                    System.out.println("u=" + u);
                } catch (Exception ex) {
                    Log.d("Codename One", "Failed to load parcelable extra from intent: " + ex.getMessage());
                }
            }
        }
        if (u != null) {
            // String scheme = intent.getScheme();
            intent.setData(null);
            if ("content".equals(scheme)) {
                try {
                    InputStream attachment = getActivity().getContentResolver().openInputStream(u);
                    if (attachment != null) {
                        String name = getContentName(getActivity().getContentResolver(), u);
                        if (name != null) {
                            String filePath = getAppHomePath() + getFileSystemSeparator() + name;
                            if (filePath.startsWith("file:")) {
                                filePath = filePath.substring(5);
                            }
                            File f = new File(filePath);
                            OutputStream tmp = createFileOuputStream(f);
                            byte[] buffer = new byte[1024];
                            int read = -1;
                            while ((read = attachment.read(buffer)) > -1) {
                                tmp.write(buffer, 0, read);
                            }
                            tmp.close();
                            attachment.close();
                            setAppArg(addFile(filePath));
                            return addFile(filePath);
                        }
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    return null;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            } else {
                /*
                    // Why do we need this special case?  u.toString()
                    // will include the full URL including query string.
                    // This special case causes urls like myscheme://part1/part2
                    // to only return "/part2" which is obviously problematic and
                    // is inconsistent with iOS.  Is this special case necessary
                    // in some versions of Android?
                    String encodedPath = u.getEncodedPath();
                    if (encodedPath != null && encodedPath.length() > 0) {
                        String query = u.getQuery();
                        if(query != null && query.length() > 0){
                            encodedPath += "?" + query;
                        }
                        setAppArg(encodedPath);
                        return encodedPath;
                    }
                    */
                if (sharedText != null) {
                    setAppArg(sharedText);
                    return sharedText;
                } else {
                    setAppArg(u.toString());
                    return u.toString();
                }
            }
        } else if (sharedText != null) {
            setAppArg(sharedText);
            return sharedText;
        }
    }
    return null;
}
Also used : BufferedInputStream(com.codename1.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BufferedOutputStream(com.codename1.io.BufferedOutputStream) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Uri(android.net.Uri) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) android.content(android.content) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MediaException(com.codename1.media.AsyncMedia.MediaException) ParseException(java.text.ParseException) SAXException(org.xml.sax.SAXException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Paint(android.graphics.Paint)

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