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();
}
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;
}
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;
}
}
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;
}
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);
}
}
Aggregations