Search in sources :

Example 1 with MutableObject

use of com.laytonsmith.PureUtilities.Common.MutableObject in project CommandHelper by EngineHub.

the class Interpreter method execute.

/**
 * This executes an entire script. The cmdline_prompt_event is first triggered (if used) and if the event is
 * cancelled, nothing happens.
 *
 * @param script
 * @param args
 * @param fromFile
 * @throws ConfigCompileException
 * @throws IOException
 */
public void execute(String script, List<String> args, File fromFile) throws ConfigCompileException, IOException, ConfigCompileGroupException {
    CmdlineEvents.cmdline_prompt_input.CmdlinePromptInput input = new CmdlineEvents.cmdline_prompt_input.CmdlinePromptInput(script, inShellMode);
    EventUtils.TriggerListener(Driver.CMDLINE_PROMPT_INPUT, "cmdline_prompt_input", input);
    if (input.isCancelled()) {
        return;
    }
    ctrlCcount = 0;
    if ("exit".equals(script)) {
        if (inShellMode) {
            inShellMode = false;
            return;
        }
        pl(YELLOW + "Use exit() if you wish to exit.");
        return;
    }
    if ("help".equals(script)) {
        pl(getHelpMsg());
        return;
    }
    if (fromFile == null) {
        fromFile = new File("Interpreter");
    }
    boolean localShellMode = false;
    if (!inShellMode && script.startsWith("$$")) {
        localShellMode = true;
        script = script.substring(2);
    }
    if (inShellMode || localShellMode) {
        // Wrap this in shell_adv
        if (doBuiltin(script)) {
            return;
        }
        List<String> shellArgs = StringUtils.ArgParser(script);
        List<String> escapedArgs = new ArrayList<>();
        for (String arg : shellArgs) {
            escapedArgs.add(new CString(arg, Target.UNKNOWN).getQuote());
        }
        script = "shell_adv(" + "array(" + StringUtils.Join(escapedArgs, ",") + ")," + "array(" + "'stdout':closure(@l){sys_out(@l);}," + "'stderr':closure(@l){sys_err(@l);})" + ");";
    }
    isExecuting = true;
    ProfilePoint compile = env.getEnv(GlobalEnv.class).GetProfiler().start("Compilation", LogLevel.VERBOSE);
    final ParseTree tree;
    try {
        TokenStream stream = MethodScriptCompiler.lex(script, fromFile, true);
        tree = MethodScriptCompiler.compile(stream);
    } finally {
        compile.stop();
    }
    // Environment env = Environment.createEnvironment(this.env.getEnv(GlobalEnv.class));
    final List<Variable> vars = new ArrayList<>();
    if (args != null) {
        // Build the @arguments variable, the $ vars, and $ itself. Note that
        // we have special handling for $0, that is the script name, like bash.
        // However, it doesn't get added to either $ or @arguments, due to the
        // uncommon use of it.
        StringBuilder finalArgument = new StringBuilder();
        CArray arguments = new CArray(Target.UNKNOWN);
        {
            // Set the $0 argument
            Variable v = new Variable("$0", "", Target.UNKNOWN);
            v.setVal(fromFile.toString());
            v.setDefault(fromFile.toString());
            vars.add(v);
        }
        for (int i = 0; i < args.size(); i++) {
            String arg = args.get(i);
            if (i > 0) {
                finalArgument.append(" ");
            }
            Variable v = new Variable("$" + Integer.toString(i + 1), "", Target.UNKNOWN);
            v.setVal(new CString(arg, Target.UNKNOWN));
            v.setDefault(arg);
            vars.add(v);
            finalArgument.append(arg);
            arguments.push(new CString(arg, Target.UNKNOWN), Target.UNKNOWN);
        }
        Variable v = new Variable("$", "", false, true, Target.UNKNOWN);
        v.setVal(new CString(finalArgument.toString(), Target.UNKNOWN));
        v.setDefault(finalArgument.toString());
        vars.add(v);
        env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(CArray.TYPE, "@arguments", arguments, Target.UNKNOWN));
    }
    try {
        ProfilePoint p = this.env.getEnv(GlobalEnv.class).GetProfiler().start("Interpreter Script", LogLevel.ERROR);
        try {
            final MutableObject<Throwable> wasThrown = new MutableObject<>();
            scriptThread = new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        MethodScriptCompiler.execute(tree, env, new MethodScriptComplete() {

                            @Override
                            public void done(String output) {
                                if (System.console() != null && !"".equals(output.trim())) {
                                    StreamUtils.GetSystemOut().println(output);
                                }
                            }
                        }, null, vars);
                    } catch (CancelCommandException e) {
                    // Nothing, though we could have been Ctrl+C cancelled, so we need to reset
                    // the interrupt flag. But we do that unconditionally below, in the finally,
                    // in the other thread.
                    } catch (ConfigRuntimeException e) {
                        ConfigRuntimeException.HandleUncaughtException(e, env);
                        // No need for the full stack trace
                        if (System.console() == null) {
                            System.exit(1);
                        }
                    } catch (NoClassDefFoundError e) {
                        StreamUtils.GetSystemErr().println(RED + Main.getNoClassDefFoundErrorMessage(e) + reset());
                        StreamUtils.GetSystemErr().println("Since you're running from standalone interpreter mode, this is not a fatal error, but one of the functions you just used required" + " an actual backing engine that isn't currently loaded. (It still might fail even if you load the engine though.) You simply won't be" + " able to use that function here.");
                        if (System.console() == null) {
                            System.exit(1);
                        }
                    } catch (InvalidEnvironmentException ex) {
                        StreamUtils.GetSystemErr().println(RED + ex.getMessage() + " " + ex.getData() + "() cannot be used in this context.");
                        if (System.console() == null) {
                            System.exit(1);
                        }
                    } catch (RuntimeException e) {
                        pl(RED + e.toString());
                        e.printStackTrace(StreamUtils.GetSystemErr());
                        if (System.console() == null) {
                            System.exit(1);
                        }
                    }
                }
            }, "MethodScript-Main");
            scriptThread.start();
            try {
                scriptThread.join();
            } catch (InterruptedException ex) {
            // 
            }
        } finally {
            p.stop();
        }
    } finally {
        env.getEnv(GlobalEnv.class).SetInterrupt(false);
        isExecuting = false;
    }
}
Also used : TokenStream(com.laytonsmith.core.compiler.TokenStream) InvalidEnvironmentException(com.laytonsmith.core.environments.InvalidEnvironmentException) IVariable(com.laytonsmith.core.constructs.IVariable) Variable(com.laytonsmith.core.constructs.Variable) IVariable(com.laytonsmith.core.constructs.IVariable) ArrayList(java.util.ArrayList) CArray(com.laytonsmith.core.constructs.CArray) CString(com.laytonsmith.core.constructs.CString) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CString(com.laytonsmith.core.constructs.CString) CmdlineEvents(com.laytonsmith.core.events.drivers.CmdlineEvents) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CancelCommandException(com.laytonsmith.core.exceptions.CancelCommandException) MutableObject(com.laytonsmith.PureUtilities.Common.MutableObject) ProfilePoint(com.laytonsmith.core.profiler.ProfilePoint) ProfilePoint(com.laytonsmith.core.profiler.ProfilePoint) MethodScriptComplete(com.laytonsmith.core.MethodScriptComplete) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) File(java.io.File) ParseTree(com.laytonsmith.core.ParseTree)

Example 2 with MutableObject

use of com.laytonsmith.PureUtilities.Common.MutableObject in project CommandHelper by EngineHub.

the class SAXDocumentTest method testAttributes.

@Test
public void testAttributes() throws Exception {
    final MutableObject m = new MutableObject();
    doc.addListener("/root/node1", new SAXDocument.ElementCallback() {

        @Override
        public void handleElement(String xpath, String tag, Map<String, String> attr, String contents) {
            m.setObject(attr.get("attribute"));
        }
    });
    doc.parse();
    assertEquals("value", m.getObject());
}
Also used : MutableObject(com.laytonsmith.PureUtilities.Common.MutableObject) Test(org.junit.Test)

Example 3 with MutableObject

use of com.laytonsmith.PureUtilities.Common.MutableObject in project CommandHelper by EngineHub.

the class PNViewer method loadFromRemote.

private void loadFromRemote(final String host, final int port, final String password, final String remoteFile) {
    remoteSocketThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                try (Socket s = new Socket()) {
                    s.connect(new InetSocketAddress(host, port), 30000);
                    remoteSocket = s;
                    setStatus("Connected to remote server", true);
                    setProgress(null);
                    try {
                        final ObjectOutputStream os = new AutoFlushObjectOutputStream(s.getOutputStream());
                        final ObjectInputStream is = new ObjectInputStream(s.getInputStream());
                        remoteOutput = os;
                        remoteInput = is;
                        // Set up our initial data
                        log("Writing client version: " + PROTOCOL_VERSION);
                        os.writeInt(PROTOCOL_VERSION);
                        switch(is.readUTF()) {
                            case "VERSION-OK":
                                break;
                            default:
                                showError("The server does not support this client's version.");
                                return;
                        }
                        os.writeUTF(password);
                        switch(is.readUTF()) {
                            case "PASSWORD-OK":
                                log("Password accepted by server.");
                                break;
                            default:
                                showError("Server rejected our password. Check the password and try again.");
                                return;
                        }
                        os.writeUTF("SET-REMOTE-FILE");
                        os.writeUTF(remoteFile);
                        final MutableObject<Map<String[], String>> data = new MutableObject<>();
                        final MutableObject<URI> sourceURI = new MutableObject<>();
                        VirtualPersistenceNetwork vpn = null;
                        connection: while (!Thread.currentThread().isInterrupted() && s.isConnected()) {
                            String serverCommand = is.readUTF();
                            switch(serverCommand) {
                                case "DISCONNECT":
                                    break connection;
                                case "FILE-OK":
                                    os.writeUTF("LOAD-DATA");
                                    reloadButton.setEnabled(false);
                                    break;
                                case "FILE-BAD":
                                    showError("Remote file doesn't exist, disconnecting.");
                                    break;
                                case "LOAD-DATA":
                                    int size = is.readInt();
                                    setStatus("Downloading data from server...", true);
                                    setProgress(0);
                                    byte[] bdata = new byte[size];
                                    for (int i = 0; i < size; i++) {
                                        bdata[i] = is.readByte();
                                        setProgress((int) ((((double) i) / ((double) size)) * 100));
                                    }
                                    setStatus("Processing data from server", true);
                                    setProgress(null);
                                    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bdata));
                                    try {
                                        Map<String[], String> d = (Map<String[], String>) ois.readObject();
                                        data.setObject(d);
                                        vpn = new VirtualPersistenceNetwork() {

                                            Map<String, URI> sources = new HashMap<>();

                                            @Override
                                            public Map<String[], String> getAllData() throws DataSourceException {
                                                return data.getObject();
                                            }

                                            @Override
                                            public URI getKeySource(String[] key) {
                                                String kk = join(key);
                                                if (!sources.containsKey(kk)) {
                                                    try {
                                                        sourceURI.setObject(null);
                                                        os.writeUTF("KEY-SOURCE");
                                                        os.writeUTF(kk);
                                                        synchronized (sourceURI) {
                                                            if (sourceURI.getObject() == null) {
                                                                try {
                                                                    sourceURI.wait();
                                                                } catch (InterruptedException ex) {
                                                                // 
                                                                }
                                                            }
                                                        }
                                                        URI uri = sourceURI.getObject();
                                                        sources.put(kk, uri);
                                                    } catch (IOException ex) {
                                                        showError(ex.getMessage());
                                                        log(ex);
                                                    }
                                                }
                                                return sources.get(kk);
                                            }
                                        };
                                        try {
                                            displayData(vpn);
                                            setStatus("Done.", false);
                                        } catch (DataSourceException ex) {
                                            log(ex);
                                            showError(ex.getMessage());
                                        }
                                    } catch (ClassNotFoundException ex) {
                                        log(ex);
                                        showError(ex.getMessage());
                                    }
                                    reloadButton.setEnabled(true);
                                    break;
                                case "KEY-SOURCE":
                                    try {
                                        URI uri = (URI) is.readObject();
                                        sourceURI.setObject(uri);
                                        synchronized (sourceURI) {
                                            sourceURI.notifyAll();
                                        }
                                    } catch (ClassNotFoundException ex) {
                                        log(ex);
                                    }
                                    break;
                                case "LOAD-ERROR":
                                    String message = is.readUTF();
                                    setStatus(message, false);
                                    showError(message);
                                    reloadButton.setEnabled(true);
                                    break;
                                default:
                                    showError("Server sent unrecognized command, disconnecting.");
                                    log("Unrecognized command: " + serverCommand);
                                    break connection;
                            }
                        }
                        log("Closing connection.");
                    } catch (EOFException ex) {
                        log(ex);
                        showError("The server closed the connection unexpectedly.");
                    }
                } catch (SocketTimeoutException ex) {
                    showError("Connection timed out, check your settings and try again.");
                } finally {
                    setStatus("Connection to remote server closed.", false);
                    remoteOutput = null;
                    remoteInput = null;
                    reloadButton.setEnabled(true);
                }
            } catch (IOException ex) {
                showError(ex.getMessage());
                Logger.getLogger(PNViewer.class.getName()).log(Level.SEVERE, null, ex);
            }
            remoteSocketThread = null;
        }
    });
    remoteSocketThread.start();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) AutoFlushObjectOutputStream(com.laytonsmith.PureUtilities.Common.AutoFlushObjectOutputStream) IOException(java.io.IOException) AutoFlushObjectOutputStream(com.laytonsmith.PureUtilities.Common.AutoFlushObjectOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) URI(java.net.URI) SocketTimeoutException(java.net.SocketTimeoutException) DataSourceException(com.laytonsmith.persistence.DataSourceException) ByteArrayInputStream(java.io.ByteArrayInputStream) EOFException(java.io.EOFException) Map(java.util.Map) HashMap(java.util.HashMap) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) ObjectInputStream(java.io.ObjectInputStream) MutableObject(com.laytonsmith.PureUtilities.Common.MutableObject)

Example 4 with MutableObject

use of com.laytonsmith.PureUtilities.Common.MutableObject in project CommandHelper by EngineHub.

the class SAXDocumentTest method testComplexContents.

@Test
public void testComplexContents() throws Exception {
    final MutableObject m = new MutableObject();
    doc.addListener("/root/outer", new SAXDocument.ElementCallback() {

        @Override
        public void handleElement(String xpath, String tag, Map<String, String> attr, String contents) {
            m.setObject(contents);
        }
    });
    doc.parse();
    assertEquals("<inner attr=\"&quot;attr&quot;\">text</inner>", m.getObject());
}
Also used : MutableObject(com.laytonsmith.PureUtilities.Common.MutableObject) Test(org.junit.Test)

Example 5 with MutableObject

use of com.laytonsmith.PureUtilities.Common.MutableObject in project CommandHelper by EngineHub.

the class SAXDocumentTest method testSimpleContents.

@Test
public void testSimpleContents() throws Exception {
    final MutableObject m = new MutableObject();
    doc.addListener("/root/nodes/inode[1]", new SAXDocument.ElementCallback() {

        @Override
        public void handleElement(String xpath, String tag, Map<String, String> attr, String contents) {
            m.setObject(contents);
        }
    });
    doc.parse();
    assertEquals("value", m.getObject());
}
Also used : MutableObject(com.laytonsmith.PureUtilities.Common.MutableObject) Test(org.junit.Test)

Aggregations

MutableObject (com.laytonsmith.PureUtilities.Common.MutableObject)5 Test (org.junit.Test)3 AutoFlushObjectOutputStream (com.laytonsmith.PureUtilities.Common.AutoFlushObjectOutputStream)1 MethodScriptComplete (com.laytonsmith.core.MethodScriptComplete)1 ParseTree (com.laytonsmith.core.ParseTree)1 TokenStream (com.laytonsmith.core.compiler.TokenStream)1 CArray (com.laytonsmith.core.constructs.CArray)1 CString (com.laytonsmith.core.constructs.CString)1 IVariable (com.laytonsmith.core.constructs.IVariable)1 Variable (com.laytonsmith.core.constructs.Variable)1 GlobalEnv (com.laytonsmith.core.environments.GlobalEnv)1 InvalidEnvironmentException (com.laytonsmith.core.environments.InvalidEnvironmentException)1 CmdlineEvents (com.laytonsmith.core.events.drivers.CmdlineEvents)1 CancelCommandException (com.laytonsmith.core.exceptions.CancelCommandException)1 ConfigRuntimeException (com.laytonsmith.core.exceptions.ConfigRuntimeException)1 ProfilePoint (com.laytonsmith.core.profiler.ProfilePoint)1 DataSourceException (com.laytonsmith.persistence.DataSourceException)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 EOFException (java.io.EOFException)1 File (java.io.File)1