Jarchi support for readfile from local filesystem

Started by rfamans, January 14, 2019, 10:43:49 AM

Previous topic - Next topic

rfamans

Hi, since it is possible to use $.fs.writeFile(filePath, text) in Jarchi, would it also be possible to use $.fs.readfile in order to consume the contents of a text file on the local filesystem?

Jean-Baptiste Sarrodie

Hi,

In fact you can already do it through Nashorn (the JAVA-based JavaScript engine). I have an example on another laptop. I will share it later today.

Regards,

JB
If you value and use Archi, please consider making a donation!
Ask your ArchiMate related questions to the ArchiMate Community's Discussion Board.


Jean-Baptiste Sarrodie

Hi,

Here it is:
function readFully(url) {
    var result = "";
    var imports = new JavaImporter(java.net, java.lang, java.io);

    with (imports) {

        var urlObj = null;

        try {
            urlObj = new URL(url);
        } catch (e) {
            // If the URL cannot be built, assume it is a file path.
            urlObj = new URL(new File(url).toURI().toURL());
        }

        var reader = new BufferedReader(new InputStreamReader(urlObj.openStream()));

        var line = reader.readLine();
        while (line != null) {
            result += line + "\n";
            line = reader.readLine();
        }

        reader.close();
    }

    return result;
}


Add this function to your jArchi script and you'll then be ale to use the readFully(url_or_filename) function.

Regards,

JB
If you value and use Archi, please consider making a donation!
Ask your ArchiMate related questions to the ArchiMate Community's Discussion Board.


rheward

I wanted to do something similar and I ended up repurposing smileham's import from CSV in this community script:
https://gist.github.com/smileham/1e57a5946235e780dee5a824f664aa3d

Jean-Baptiste Sarrodie

Hi,

Credit where credit's due : this is not my own implementation but I found it here.

Something interresting to know is that jArchi uses Nashorn which is the JavaScript engine embedded inside any JVM. This means that you have access to the whole underlying Java environment, ie. all classes.

This is very similar to NodeJS with the main difference being that NodeJS also provides a DOM (like any browser) to ease HTML document manipulation.

If you google it a bit, you'll find several code snippets and tips & tricks for Nashorn, including some polyfills to make it react a bit more like NodeJS. Some people also succeeded in loading a full-JS DOM implementation, making it easy to manipulate HTML document before loading them in the browser window included with jArchi.

Here are some links of interrest:

Regards,

JB
If you value and use Archi, please consider making a donation!
Ask your ArchiMate related questions to the ArchiMate Community's Discussion Board.