use of com.codename1.io.File in project CodenameOne by codenameone.
the class ResourcesMutator method createScreenshots.
/**
* Creates screenshots for the given HTML which was generated by {@link CSSTheme#generateCaptureHtml() }.
* @param web The web View used to render the HTML
* @param html The HTML to render in the webview. Generated by {@link CSSTheme#generateCaptureHtml() }
* @param baseURL The BaseURL - general points to the CSS file location. Used for loading resources from relative paths.
*/
public void createScreenshots(BrowserComponent web, String html, String baseURL) {
// System.out.println("in createScreenshots");
try {
File baseURLFile = new File(new URL(baseURL).toURI());
if (!baseURLFile.isDirectory()) {
baseURLFile = baseURLFile.getParentFile();
}
startWebServer(baseURLFile);
boolean[] waitForServerResult = new boolean[1];
CN.invokeAndBlock(new Runnable() {
public void run() {
waitForServerResult[0] = webServer.waitForServer(2000);
}
});
if (!waitForServerResult[0]) {
throw new RuntimeException("Failed to start webserver after 2 seconds");
}
} catch (Exception ex) {
throw new RuntimeException("Failed to start local webserver for creating screenshots", ex);
}
long timeout = 50000;
// String captureSrc = this.getClass().getResource("capture.js").toExternalForm();
String captureJS = null;
try {
captureJS = Util.readToString(this.getClass().getResourceAsStream("capture.js"));
} catch (IOException ex) {
throw new RuntimeException("Failed to read capture.js file.", ex);
}
// final String modifiedHtml = html.replace("</body>", /*"<script src=\"https://code.jquery.com/jquery-2.1.4.min.js\">"
// + */"</script><script src=\""+captureSrc+"\"></script></body>");
final String modifiedHtml = html.replace("</head>", /*"<script src=\"https://code.jquery.com/jquery-2.1.4.min.js\">"
+ */
"<script>\n" + captureJS + "\n</script></head>");
this.web = web;
screenshotsComplete = false;
CN.callSerially(() -> {
loadListener = (ActionEvent evt) -> {
if (webServer != null) {
webServer.stop();
webServer = null;
}
web.removeWebEventListener(BrowserComponent.onLoad, loadListener);
try {
// System.out.println("In onLoad event");
// Use reflection to retrieve the WebEngine's private 'page' field.
web.addJSCallback("window.app = window.app || {}; window.app.createScreenshotCallback = function(id, x, y, w, h) {" + "callback.onSuccess(JSON.stringify({id:id, x:x, y:y, w:w, h:h}));" + "};", res -> {
try {
Result data = Result.fromContent(new StringReader(res.toString()), Result.JSON);
createScreenshotCallback(data.getAsString("id"), data.getAsInteger("x"), data.getAsInteger("y"), data.getAsInteger("w"), data.getAsInteger("h"));
} catch (Exception ex) {
Log.p("Failed to parse input to createScreenshotsCallback");
Log.e(ex);
}
});
web.addJSCallback("window.app.finishedCaptureScreenshotsCallback = function() {" + "callback.onSuccess(null);" + "};", res -> {
finishedCaptureScreenshotsCallback();
});
web.execute("$(document).ready(function(){ captureScreenshots();});");
// web.getEngine().executeScript("window.onload = function(){window.app.ready()};");
} catch (IllegalArgumentException ex) {
Logger.getLogger(CN1CSSCompiler.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(CN1CSSCompiler.class.getName()).log(Level.SEVERE, null, ex);
}
};
web.addWebEventListener(BrowserComponent.onLoad, loadListener);
// CN.setProperty("cef.setPage.useDataURI", "true");
webServer.route("/index.html", () -> {
try {
return modifiedHtml.getBytes("UTF-8");
} catch (Exception ex) {
Log.e(ex);
try {
return ("Error: " + ex.getMessage()).getBytes("UTF-8");
} catch (Exception ex2) {
Log.e(ex2);
return new byte[0];
}
}
});
web.setURL("http://localhost:" + webServer.getPort() + "/index.html");
});
long startTime = System.currentTimeMillis();
while (!screenshotsComplete && System.currentTimeMillis() - startTime < timeout) {
CN.invokeAndBlock(new Runnable() {
public void run() {
Util.wait(screenshotsLock, 50);
}
});
}
if (!screenshotsComplete) {
throw new RuntimeException("Failed to create screenshots for HTML " + html + ". Timeout reached. Likely there was a problem initializing the browser component.");
}
this.web = null;
this.loadListener = null;
}
use of com.codename1.io.File in project CodenameOne by codenameone.
the class URITests method runTest.
@Override
public boolean runTest() throws Exception {
FileSystemStorage fs = FileSystemStorage.getInstance();
String home = fs.getAppHomePath();
if (!home.endsWith(fs.getFileSystemSeparator() + "")) {
home += fs.getFileSystemSeparator();
}
String homePath = home.substring(6);
homePath = StringUtil.replaceAll(homePath, "\\", "/");
while (homePath.startsWith("/")) {
homePath = homePath.substring(1);
}
homePath = "/" + homePath;
com.codename1.io.URL url = new com.codename1.io.File("hello world.txt").toURL();
// https://en.wikipedia.org/wiki/File_URI_scheme
assertTrue(url.toString().startsWith("file:/"), "URL should start with file:///");
assertEqual("file:" + homePath + "hello%20world.txt", url.toString(), "URL failed to encode space in file name");
URI uri = new com.codename1.io.File("hello world.txt").toURI();
assertEqual("file:" + homePath + "hello%20world.txt", uri.toString(), "URI failed to encode space in file name");
assertEqual(homePath + "hello world.txt", uri.getPath(), "Incorrect URI path");
return true;
}
use of com.codename1.io.File in project CodenameOne by codenameone.
the class DatabaseTests method testSimpleQueriesInCustomPath.
private void testSimpleQueriesInCustomPath() throws Exception {
if (Database.isCustomPathSupported()) {
String dbName = new File("somedir/testdb").getAbsolutePath();
new File(dbName).getParentFile().mkdirs();
Database.delete(dbName);
Database db = Database.openOrCreate(dbName);
db.execute("create table tests (name text)");
db.execute("insert into tests values ('Steve'), ('Mike'), ('Ryan')");
Cursor c = db.executeQuery("select count(*) from tests");
c.next();
this.assertEqual(3, c.getRow().getInteger(0), "Expected result of 3 for count(*) after inserting 3 rows");
} else {
Log.p("testSimpleQueriesInCustomPath skipped on this platform");
}
}
use of com.codename1.io.File in project CodenameOne by codenameone.
the class DatabaseTests method testCustomPaths.
private void testCustomPaths() throws Exception {
if (Database.isCustomPathSupported()) {
File dbFile = new File("somedir/testdb");
dbFile.getParentFile().mkdirs();
String dbName = dbFile.getAbsolutePath();
// Start out fresh
Database.delete(dbName);
Database db = Database.openOrCreate(dbName);
this.assertNotNull(db, "Failed to open database with custom path " + dbName);
this.assertTrue(Database.exists(dbName), "Database.exists() returns false after openOrCreate with custom path: " + dbName);
String path = Database.getDatabasePath(dbName);
this.assertTrue(FileSystemStorage.getInstance().exists(path), "Database doesn't exist after creation with custom path: " + dbName);
this.assertEqual(dbFile.getAbsolutePath(), path, "Result of getDatabasePath() doesn't match input path with custom path");
db.close();
Database.delete(dbName);
this.assertTrue(!FileSystemStorage.getInstance().exists(path), "Failed to delete database with custom path: " + dbName);
} else {
Throwable ex = null;
File dbFile = new File("somedir/testdb");
dbFile.getParentFile().mkdirs();
String dbName = dbFile.getAbsolutePath();
try {
Database.openOrCreate(dbName);
} catch (Throwable t) {
ex = t;
}
this.assertTrue(ex instanceof IllegalArgumentException, "Platforms that don't support custom paths should throw an illegalArgumentException when trying to open databases with file separators in them");
ex = null;
try {
Database.exists(dbName);
} catch (Throwable t) {
ex = t;
}
this.assertTrue(ex instanceof IllegalArgumentException, "Platforms that don't support custom paths should throw an illegalArgumentException when trying to open databases with file separators in them");
ex = null;
try {
Database.delete(dbName);
} catch (Throwable t) {
ex = t;
}
this.assertTrue(ex instanceof IllegalArgumentException, "Platforms that don't support custom paths should throw an illegalArgumentException when trying to open databases with file separators in them");
ex = null;
try {
Database.getDatabasePath(dbName);
} catch (Throwable t) {
ex = t;
}
this.assertTrue(ex instanceof IllegalArgumentException, "Platforms that don't support custom paths should throw an illegalArgumentException when trying to open databases with file separators in them");
}
}
use of com.codename1.io.File in project CodenameOne by codenameone.
the class FileSystemTests method runTest.
@Override
public boolean runTest() throws Exception {
testFileClass();
FileSystemStorage fs = FileSystemStorage.getInstance();
String homePath = fs.getAppHomePath();
this.assertTrue(homePath.startsWith("file://"), "App Home Path should start with file:// but was " + homePath);
String testFileContents = "Hello World";
String testFilePath = homePath + fs.getFileSystemSeparator() + "testfile.txt";
try (OutputStream os = fs.openOutputStream(testFilePath)) {
os.write(testFileContents.getBytes("UTF-8"));
}
this.assertTrue(fs.exists(testFilePath), "Created file " + testFilePath + " but fs says it doesn't exist");
String readContents = null;
try (InputStream is = fs.openInputStream(testFilePath)) {
byte[] buf = testFileContents.getBytes("UTF-8");
for (int i = 0; i < buf.length; i++) {
buf[i] = (byte) 0;
}
int len = is.read(buf);
this.assertEqual(buf.length, len, "Bytes read didn't match expected");
readContents = new String(buf, "UTF-8");
}
this.assertEqual(testFileContents, readContents, "Contents of file doesn't match expected contents after write and read");
return true;
}
Aggregations