Search in sources :

Example 11 with URL

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

the class WebPushTest method createPushForm.

void createPushForm() {
    Form f = new Form("Test Push", new BorderLayout());
    TextField serverUrl = new TextField("https://push.codenameone.com/push/push");
    String nexus5XEmulatorId = "cn1-fcm-c_t22hK-weg:APA91bGNa2hP9SHLBhUmLmzY1ANyjCH2ydEQz0JUFlMPFUHDAUfTQysC1r9K6I7jdk5LN6mEP5k5IWvyQX4dvubbHeY1KWQRKb-aYuXaHHHg2U3XGH1xXXa7xfJbsCf7nB0vu1aWhOg_4M4Z-znC2X5a0tpYf59QmA";
    // APA91bHWiuoPMA4OgIr3ZyVgSjVmnh4H0BQ4jhB3hblIAZfmMs-SfRN1tb4662MudPEULjIkl8P_oTrQ14sKgowz4Q45n6iaPl1GwXb_9HbtlAQDAlnX60Eo4SamzZJkB_6kcnsEMKt_
    String iphoneId = "cn1-ios-c76b23de81f6389f37d2621f000b7f01c52e5c1d6f1f947b199a7c2d8844f713";
    TextArea targetId = new TextArea(Preferences.get("targetId", ""));
    targetId.addActionListener(e -> Preferences.set("targetId", targetId.getText()));
    TextField pushType = new TextField(Preferences.get("pushType", "99"));
    pushType.addActionListener(e -> Preferences.set("pushType", pushType.getText()));
    TextField payload = new TextField(Preferences.get("payload", "<push type=\"0\" body=\"Hello\" category=\"fo\"/>"));
    payload.addActionListener(e -> Preferences.set("payload", payload.getText()));
    TextField gcmServerKey = new TextField(Preferences.get("gcmServerKey", ""));
    gcmServerKey.setHint("FCM_SERVER_API_KEY");
    gcmServerKey.addActionListener(e -> Preferences.set("gcmServerKey", gcmServerKey.getText()));
    TextField tokenField = new TextField(Preferences.get("token", ""));
    tokenField.setHint("Enter your CN1 Token");
    tokenField.addActionListener(e -> {
        Preferences.set("token", tokenField.getText());
    });
    targetId.setRows(4);
    targetId.getAllStyles().setFgColor(0x0);
    targetId.getAllStyles().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL));
    Button send = new Button("Send");
    send.addActionListener(e -> {
        /*
            boolean result = new Push("E729F5CE-DCE8-4D63-B517-85112994EC66", payload.getText(), targetId.getText())
                    .gcmAuth(gcmServerKey.getText())
                    .apnsAuth(IOS_DEV_CERT_URL, IOS_DEV_CERT_PASS, false)
                    .pushType(Integer.parseInt(pushType.getText()))
                    .wnsAuth("xxxxx", "xxxxxxxx")
                    .send()
                    //.sendAsync()
                    ;
            
            System.out.println("Push sent.  Result: "+result);
            */
        ConnectionRequest req = new ConnectionRequest();
        req.setUrl(serverUrl.getText());
        req.addArgument("token", tokenField.getText());
        req.addArgument("device", targetId.getText());
        req.addArgument("body", payload.getText());
        req.addArgument("type", pushType.getText());
        req.addArgument("auth", gcmServerKey.getText());
        req.addArgument("cert", IOS_DEV_CERT_URL);
        req.addArgument("certPassword", IOS_DEV_CERT_PASS);
        req.addArgument("sid", "ms-app://xxxxxxxxx");
        req.addArgument("client_secret", "xxxxxxxxx");
        req.setHttpMethod("POST");
        req.setPost(true);
        NetworkManager.getInstance().addToQueueAndWait(req);
        System.out.println(req.getResponseCode());
        try {
            System.out.println(new String(req.getResponseData(), "UTF-8"));
        } catch (Throwable t) {
            Log.e(t);
        }
    // new Push("E729F5CE-DCE8-4D63-B517-85112994EC66", payload.getText(), targetId.getText())
    // .wnsAuth("ms-app://s-1-15-2-2674027049-292503787-1918612089-438606370-903203898-836476968-4131729547", "2S37cRtqCR3vQVqhfrFBA2w6PAsWwZ/m")
    // .send();
    });
    Container center = BoxLayout.encloseY(new Label("Server URL"), serverUrl, new Label("Target ID"), targetId, new Label("Push Type"), pushType, new Label("Payload"), payload, new Label("GCM Server Key"), gcmServerKey, new Label("Codename One Token"), tokenField, send);
    center.setScrollableY(true);
    f.add(BorderLayout.CENTER, center);
    f.show();
}
Also used : Container(com.codename1.ui.Container) ConnectionRequest(com.codename1.io.ConnectionRequest) BorderLayout(com.codename1.ui.layouts.BorderLayout) Form(com.codename1.ui.Form) TextArea(com.codename1.ui.TextArea) Button(com.codename1.ui.Button) Label(com.codename1.ui.Label) TextField(com.codename1.ui.TextField)

Example 12 with URL

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

the class HTTPUtil method update.

public static boolean update(URL u, File destFile, File tempDir, boolean requireHttps, boolean requireFingerprintMatch, boolean forceCheck) throws IOException, HttpsRequiredException, FingerprintChangedException {
    if (destFile.exists() && "github.com".equals(u.getHost()) && u.getPath().contains("/releases/download/")) {
        logger.fine("Github release assets should not require updating.");
        return false;
    }
    if (!forceCheck && getExpiryDate(destFile) > System.currentTimeMillis()) {
        return false;
    }
    File etagFile = new File(destFile.getParentFile(), destFile.getName() + ".etag");
    if (destFile.exists() && etagFile.exists()) {
        String etag;
        try (InputStream is = new FileInputStream(etagFile)) {
            etag = readToString(is).trim();
        }
        DownloadResponse resp = new DownloadResponse();
        if (doesETagMatch(resp, u, etag)) {
            saveExpires(resp, destFile);
            return false;
        }
        saveExpires(resp, destFile);
    }
    File sha1File = new File(destFile.getParentFile(), destFile.getName() + ".sha1");
    File tempFile = File.createTempFile(destFile.getName(), "progress", tempDir);
    Fingerprints.clear();
    DownloadResponse resp = new DownloadResponse();
    download(resp, u, tempFile, requireHttps);
    if (u.getProtocol() == "https") {
        String newFingerprint = Fingerprints.get(u.getHost());
        if (newFingerprint != null) {
            if (requireFingerprintMatch && sha1File.exists()) {
                String lastFingerprint = FileUtil.readFileToString(sha1File).trim();
                if (!lastFingerprint.equals(newFingerprint)) {
                    throw new FingerprintChangedException(u, destFile);
                }
            } else {
                if (sha1File.exists()) {
                    String existingFingerprint = FileUtil.readFileToString(sha1File).trim();
                    if (!existingFingerprint.equals(newFingerprint)) {
                        FileUtil.writeStringToFile(newFingerprint, sha1File);
                    }
                } else {
                    FileUtil.writeStringToFile(newFingerprint, sha1File);
                }
            }
        } else {
            if (requireFingerprintMatch) {
                throw new FingerprintChangedException(u, destFile);
            }
        }
    }
    String etag0 = ETags.get(u.toString());
    if (etag0 != null) {
        FileUtil.writeStringToFile(etag0, new File(destFile.getParentFile(), destFile.getName() + ".etag"));
    }
    saveExpires(resp, destFile);
    FileUtil.writeStringToFile(u.toString(), new File(destFile.getParentFile(), destFile.getName() + ".src"));
    Files.move(tempFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    return true;
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOUtil.readToString(com.codename1.samples.IOUtil.readToString) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 13 with URL

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

the class HTTPUtil method doesETagMatch.

// public static boolean doesETagMatch(URL url, String etag) throws IOException {
// return doesETagMatch(url, etag, true);
// }
// public static boolean doesETagMatch(URL url, String etag, boolean followRedirects) throws IOException {
// return doesETagMatch(null, url, etag, followRedirects);
// }
public static boolean doesETagMatch(DownloadResponse resp, URL url, String etag, boolean followRedirects) throws IOException {
    if (etag == null) {
        return false;
    }
    // log("Checking etag for "+url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (resp != null) {
        resp.setConnection(conn);
    }
    if (Boolean.getBoolean("client4j.disableHttpCache")) {
        conn.setUseCaches(false);
        conn.setDefaultUseCaches(false);
    }
    conn.setRequestMethod("HEAD");
    // https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download
    conn.setInstanceFollowRedirects(followRedirects);
    int response = conn.getResponseCode();
    logger.fine("" + conn.getHeaderFields());
    String newETag = conn.getHeaderField("ETag");
    if (newETag != null) {
        return etag.equals(ETags.sanitize(newETag));
    } else {
        return false;
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) IOUtil.readToString(com.codename1.samples.IOUtil.readToString) CertificateUtil.getSHA1Fingerprint(com.codename1.samples.CertificateUtil.getSHA1Fingerprint)

Example 14 with URL

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

the class HTTPUtil method download.

public static File download(DownloadResponse resp, URL u, File f, boolean requireHttps) throws IOException, HttpsRequiredException {
    URLConnection conn = u.openConnection();
    if (Boolean.getBoolean("client4j.disableHttpCache")) {
        conn.setUseCaches(false);
    }
    if (conn instanceof HttpURLConnection) {
        HttpURLConnection http = (HttpURLConnection) conn;
        http.setInstanceFollowRedirects(true);
        if (resp != null) {
            resp.setConnection(http);
        }
        int responseCode = http.getResponseCode();
        if (responseCode < 200 && responseCode >= 300) {
            throw new IOException("Failed to downlod url " + u + " to file " + f + ".  HTTP response code was " + responseCode + " and response message was " + http.getResponseMessage());
        }
        String etag = http.getHeaderField("ETag");
        if (etag != null) {
            ETags.add(u.toString(), etag);
        }
    }
    if (conn instanceof HttpsURLConnection) {
        try {
            Certificate cert = ((HttpsURLConnection) conn).getServerCertificates()[0];
            if (cert instanceof X509Certificate) {
                try {
                    String newFingerprint = getSHA1Fingerprint((X509Certificate) cert).trim();
                    Fingerprints.add(u.getHost(), newFingerprint);
                } catch (CertificateEncodingException ex) {
                    Logger.getLogger(HTTPUtil.class.getName()).log(Level.SEVERE, null, ex);
                    throw new IOException(ex);
                }
            } else {
                throw new IOException("Unsupported certificate type: " + cert.getClass().getName());
            }
        } catch (SSLPeerUnverifiedException ex) {
            throw new IOException(ex);
        }
    } else if (requireHttps) {
        throw new HttpsRequiredException(u, f);
    }
    try (InputStream input = conn.getInputStream()) {
        try (FileOutputStream output = new FileOutputStream(f)) {
            byte[] buf = new byte[128 * 1024];
            long total = conn.getContentLengthLong();
            long read = 0l;
            int len;
            while ((len = input.read(buf)) >= 0) {
                read += len;
                output.write(buf, 0, len);
                updateProgress(u, read, total);
            }
        }
    }
    return f;
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) IOUtil.readToString(com.codename1.samples.IOUtil.readToString) HttpURLConnection(java.net.HttpURLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) URLConnection(java.net.URLConnection) CertificateUtil.getSHA1Fingerprint(com.codename1.samples.CertificateUtil.getSHA1Fingerprint) X509Certificate(java.security.cert.X509Certificate) HttpURLConnection(java.net.HttpURLConnection) FileOutputStream(java.io.FileOutputStream) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 15 with URL

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

the class AnalyticsService method visitPage.

/**
 * Subclasses should override this method to track page visits
 * @param page the page visited
 * @param referer the page from which the user came
 */
protected void visitPage(String page, String referer) {
    if (lastRequest != null) {
        final String fPage = page;
        final String fReferer = referer;
        ActionListener onComplete = new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                visitPage(fPage, fReferer);
            }
        };
        lastRequest.addResponseListener(onComplete);
        lastRequest.addResponseCodeListener(onComplete);
        lastRequest.addExceptionListener(onComplete);
        return;
    }
    if (appsMode) {
        // https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#apptracking
        final ConnectionRequest req = GetGARequest();
        req.addArgument("t", "appview");
        req.addArgument("an", Display.getInstance().getProperty("AppName", "Codename One App"));
        String version = Display.getInstance().getProperty("AppVersion", "1.0");
        req.addArgument("av", version);
        req.addArgument("cd", page);
        ActionListener onComplete = new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                if (req == lastRequest) {
                    lastRequest = null;
                }
            }
        };
        req.addResponseListener(onComplete);
        req.addResponseCodeListener(onComplete);
        req.addExceptionListener(onComplete);
        lastRequest = req;
        decorateVisitPageRequest(page, referer, req);
        NetworkManager.getInstance().addToQueue(req);
    } else {
        String url = Display.getInstance().getProperty("cloudServerURL", "https://codename-one.appspot.com/") + "anal";
        final ConnectionRequest r = new ConnectionRequest();
        r.setUrl(url);
        r.setPost(false);
        r.setFailSilently(failSilently);
        r.addArgument("guid", "ON");
        r.addArgument("utmac", instance.agent);
        r.addArgument("utmn", Integer.toString((int) (System.currentTimeMillis() % 0x7fffffff)));
        if (page == null || page.length() == 0) {
            page = "-";
        }
        r.addArgument("utmp", page);
        if (referer == null || referer.length() == 0) {
            referer = "-";
        }
        r.addArgument("utmr", referer);
        r.addArgument("d", instance.domain);
        r.setPriority(ConnectionRequest.PRIORITY_LOW);
        if (timeout > 0) {
            r.setTimeout(timeout);
        }
        if (readTimeout > 0) {
            r.setReadTimeout(readTimeout);
        }
        ActionListener onComplete = new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                if (r == lastRequest) {
                    lastRequest = null;
                }
            }
        };
        r.addResponseListener(onComplete);
        r.addResponseCodeListener(onComplete);
        r.addExceptionListener(onComplete);
        lastRequest = r;
        decorateVisitPageRequest(page, referer, r);
        NetworkManager.getInstance().addToQueue(r);
    }
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) ActionListener(com.codename1.ui.events.ActionListener) ActionEvent(com.codename1.ui.events.ActionEvent)

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