use of com.codename1.io.URL in project CodenameOne by codenameone.
the class JavaFXLoader method downloadJavaFX.
private void downloadJavaFX() throws IOException {
try {
String url = getJavaFXURL();
if (url == null) {
throw new RuntimeException("No JavaFX URL found for this platform");
}
if (javafxDir.exists()) {
delTree(javafxDir);
}
javafxDir.getParentFile().mkdirs();
File javafxZip = new File(javafxDir.getParentFile(), "javafx.zip");
downloadToFile(url, javafxZip);
System.out.println("Downladed " + javafxZip + " " + javafxZip.length() + " bytes");
File tmpDir = new File(javafxZip.getParentFile(), "javafx.tmp." + System.currentTimeMillis());
try {
new UnzipUtility().unzip(javafxZip.getAbsolutePath(), tmpDir.getAbsolutePath());
javafxDir.mkdir();
File libDirTmp = findDir(tmpDir, "lib");
File legalDirTmp = findDir(tmpDir, "legal");
File binDirTmp = findDir(tmpDir, "bin");
if (libDirTmp == null || !libDirTmp.exists()) {
throw new IOException("No lib dir found within JavaFX zip");
}
// System.out.println("Files:");
// for (File f : libDirTmp.listFiles()) {
// System.out.println(f);
// if (f.isDirectory()) {
// for (File child : f.listFiles()) {
// System.out.println(" "+child);
// }
// }
// }
// if (legalDirTmp == null || !legalDirTmp.exists()) {
// throw new IOException("No legal dir found within JavaFX zip");
// }
libDirTmp.renameTo(new File(javafxDir, "lib"));
if (legalDirTmp != null && legalDirTmp.exists()) {
legalDirTmp.renameTo(new File(javafxDir, "legal"));
}
if (binDirTmp != null && binDirTmp.exists()) {
binDirTmp.renameTo(new File(javafxDir, "bin"));
}
} finally {
delTree(tmpDir);
javafxZip.delete();
}
} catch (MalformedURLException ex) {
Logger.getLogger(JavaFXLoader.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException(ex);
}
}
use of com.codename1.io.URL in project CodenameOne by codenameone.
the class CEFBrowserComponent method create.
public static CEFBrowserComponent create(final String startingURL, final CEFBrowserComponentListener parent) {
CefSettings settings = new CefSettings();
String[] args = createArgs();
// Perform startup initialization on platforms that require it.
if (!"true".equals(System.getProperty("cef.started", "false"))) {
if (!CefApp.startup(args)) {
System.err.println("CEFStartup initialization failed");
throw new RuntimeException("CEF Startup initialization failed!");
}
System.setProperty("cef.started", "true");
}
// OSR mode is enabled by default on Linux.
// and disabled by default on Windows and Mac OS X.
boolean osrEnabledArg = true;
boolean transparentPaintingEnabledArg = true;
boolean createImmediately = true;
for (String arg : args) {
arg = arg.toLowerCase();
if (arg.equals("--off-screen-rendering-enabled")) {
osrEnabledArg = true;
} else if (arg.equals("--transparent-painting-enabled")) {
transparentPaintingEnabledArg = true;
} else if (arg.equals("--create-immediately")) {
createImmediately = true;
}
}
CEFPeerComponentBuffer buffer = new CEFPeerComponentBuffer();
final WeakReference<CEFBrowserComponentListener> parentRef = new WeakReference<CEFBrowserComponentListener>(parent);
BrowserNavigationCallback navigationCallback = new BrowserNavigationCallback() {
private CEFBrowserComponentListener l = parentRef.get();
@Override
public boolean shouldNavigate(String url) {
// CEFBrowserComponentListener l = parentRef.get();
if (l != null) {
return l.shouldNavigate(url);
}
return false;
}
};
final BrowserPanel panel = new BrowserPanel(startingURL, buffer, navigationCallback, osrEnabledArg, transparentPaintingEnabledArg, createImmediately, args) {
private CEFBrowserComponentListener p = parentRef.get();
@Override
protected void onError(ActionEvent l) {
// CEFBrowserComponentListener p = parentRef.get();
if (p != null) {
p.onError(l);
}
}
@Override
protected void onStart(ActionEvent l) {
if (p != null) {
p.onStart(l);
}
}
@Override
protected void onLoad(ActionEvent l) {
if (p != null) {
p.onLoad(l);
}
}
};
java.awt.Container cnt = JavaSEPort.instance.getCanvas().getParent();
while (!(cnt instanceof JFrame)) {
cnt = cnt.getParent();
if (cnt == null) {
System.err.println("CEFBrowserComponent requires a JFrame as an ancestor. None found. Returning null");
return null;
}
}
final CEFBrowserComponent out = new CEFBrowserComponent((JFrame) cnt, panel);
out.setPeerComponentBuffer(buffer);
final WeakReference<CEFBrowserComponent> weakRef = new WeakReference<CEFBrowserComponent>(out);
panel.setReadyCallback(new Runnable() {
public void run() {
CEFBrowserComponent callback = weakRef.get();
if (callback != null) {
callback.fireReady();
}
}
});
return out;
}
use of com.codename1.io.URL in project CodenameOne by codenameone.
the class TestComponent method testCookies.
private void testCookies() throws IOException {
Cookie.clearCookiesFromStorage();
String baseUrl = "https://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()) : "");
}
use of com.codename1.io.URL in project CodenameOne by codenameone.
the class TestComponent method testBrowserComponent2267.
// Test for https://github.com/codenameone/CodenameOne/issues/2267
private void testBrowserComponent2267() {
if (!BrowserComponent.isNativeBrowserSupported()) {
return;
}
Form hi = new Form();
String formName = "testBrowserComponent2267";
hi.setName(formName);
hi.setLayout(new BorderLayout());
BrowserComponent browserComponent = new BrowserComponent();
hi.add(BorderLayout.CENTER, browserComponent);
final Throwable[] ex = new Throwable[1];
final boolean[] complete = new boolean[1];
Button loadButton = new Button("setUrl");
String buttonName = "setUrl";
loadButton.setName(buttonName);
loadButton.addActionListener((ev) -> {
ActionListener errorHandler = new ActionListener() {
public void actionPerformed(ActionEvent e) {
e.consume();
ex[0] = (Throwable) e.getSource();
complete[0] = true;
Display.getInstance().removeEdtErrorHandler(this);
}
};
try {
Display.getInstance().addEdtErrorHandler(errorHandler);
browserComponent.addWebEventListener("onLoad", e -> {
Display.getInstance().removeEdtErrorHandler(errorHandler);
complete[0] = true;
});
browserComponent.setURL("https://www.google.es");
} catch (Throwable t) {
ex[0] = t;
complete[0] = true;
Display.getInstance().removeEdtErrorHandler(errorHandler);
} finally {
// complete[0] = true;
}
});
hi.add(BorderLayout.SOUTH, loadButton);
hi.show();
log("About to wait for form " + formName);
TestUtils.waitForFormName(formName, 4000);
log("Finished waiting for form " + formName);
TestUtils.clickButtonByName(buttonName);
log("Waiting for browserComponent to load https://www.google.es");
while (!complete[0]) {
Display.getInstance().invokeAndBlock(() -> {
Util.sleep(50);
});
}
log("Finished waiting for browserComponent to load https://www.google.es");
String message = null;
if (ex[0] != null) {
message = ex[0].getMessage();
}
TestUtils.assertBool(ex[0] == null, "We received an exception setting the browserComponent URL: " + message);
}
use of com.codename1.io.URL in project CodenameOne by codenameone.
the class FileSystemTests method testFileClass.
private void testFileClass() throws Exception {
FileSystemStorage fs = FileSystemStorage.getInstance();
String appRoot = fs.getAppHomePath();
if (!appRoot.endsWith("" + fs.getFileSystemSeparator())) {
appRoot += fs.getFileSystemSeparator();
}
String appRootPath = appRoot.substring(6);
appRootPath = StringUtil.replaceAll(appRootPath, "\\", "/");
while (appRootPath.startsWith("/")) {
appRootPath = appRootPath.substring(1);
}
appRootPath = "/" + appRootPath;
String appRootUrl = StringUtil.replaceAll("file:" + appRootPath, " ", "%20");
assertTrue(appRoot.startsWith("file:/"), "App root doesn't start with file:/");
File hello = new File("hello world.txt");
assertEqual(appRoot + "hello world.txt", hello.getAbsolutePath(), "Incorrect absolute path for file");
assertEqual(appRootUrl + "hello%20world.txt", hello.toURL().toString(), "Incorrect URL.");
String contents = "hello world " + System.currentTimeMillis();
// Let's try writing to the file
try (OutputStream os = fs.openOutputStream(hello.getAbsolutePath())) {
os.write(contents.getBytes("UTF-8"));
}
// Read in the contents via the URL's open stream.
try (InputStream is = hello.toURL().openStream()) {
String readContent = Util.readToString(is);
assertEqual(contents, readContent, "Contents file differed after reading using URL.openStream()");
} catch (IOException fex) {
throw new RuntimeException("Failed to open stream for url " + hello, fex);
}
contents = "<!doctype html><html><head><title>Hello World</title></head><body><div id='hello'>Hello World</div></body></html>";
hello = new File("hello world.html");
try (OutputStream os = hello.toURL().openConnection().getOutputStream()) {
os.write(contents.getBytes("UTF-8"));
}
// Read in the contents via the URL's open stream.
try (InputStream is = hello.toURL().openStream()) {
String readContent = Util.readToString(is);
assertEqual(contents, readContent, "Contents file differed after reading using URL.openStream()");
} catch (IOException fex) {
throw new RuntimeException("Failed to open stream for url " + hello, fex);
}
// TODO: Find out why this test fails.
if (false && BrowserComponent.isNativeBrowserSupported()) {
BrowserComponent bc = new BrowserComponent();
Res res = new Res();
bc.addWebEventListener("onLoad", e -> {
Log.p("URL: " + bc.getURL());
if (!"Hello World".equals(bc.getTitle())) {
res.error = new RuntimeException("Incorrect page title. Should be Hello World but was " + bc.getTitle());
}
JavascriptContext ctx = new JavascriptContext(bc);
Log.p("Inner html: " + ctx.get("document.getElementById('hello').innerHTML"));
synchronized (res) {
res.complete = true;
res.notifyAll();
}
});
bc.setURL(hello.toURL().toString());
while (!res.complete) {
Display.getInstance().invokeAndBlock(() -> {
Util.sleep(100);
});
}
if (res.error != null) {
assertNull(res.error, res.error.getMessage());
}
}
}
Aggregations