Execute code from a string?

I have a Java program that draws lots of different types of curves.
I need to program how to save a drawing to a file.
It would be easiest to make a file that has the string of the code which recreates the drawing.
Is it possible to execute the content of a string?
A trivial example would be you declare an integer
int number
and you execute the string
"number = 10"
so that the value of number becomes 10.
Is this possible?

However, how does your program draw the curve in the first place? What I mean is, if it draws the curve in response to some informatiion from the user, why not save that information as text and then draw the curve the same way when the text is read again later.

Similar Messages

  • How to execute code from a text file?

    Hello all!
    How to execute some code lines from a text file? For example my file is:
    String varname = "somecontents";
    JFrame frame = new JFrame();
    frame.setVisible(true);How can I get contents of this file and parse them if I want get new JFrame and access to the variable varname?

    I mean the PHP would generate a readable Java source,
    for example some variables with some data, and I just
    dont know what to do with file if I want generate the
    xls file from my saved data, could You help? :)Some variables, some data, PHP, Java, XLS file??? Al rather vague.
    You need to explain in more detail what it is you're trying to do if you want an answer to your question!

  • How to execute code saved in string variable??

    Hello experts,
    I need to execute a select which I obtain concatenating several fields into string variable.
    So the select is saved in a string:
    var  = 'select... from ... where...'.
    There is any way to execute that select? ("exec var." or similar??)
    thanks

    Hello Illie
    Would it not be possible to use a simple dynamic SELECT, e.g.:
    DATA:
      ldo_data   TYPE REF TO data.
    FIELD-SYMBOLS:
      <lt_itab>  TYPE TABLE.
    CREATE DATA ldo_data TYPE TABLE OF (ld_tabname).
    ASSIGN ldo_data->* TO <lt_itab>.
    SELECT * from (ld_tabname) INTO TABLE <lt_itab>
       WHERE (ld_clause_string).
    Regards
      Uwe

  • Executing code from a Bean only once when page loads

    Hi all,
    I have a method in a BackingBean which access UI Bindings from my fragment: xxx.jsff.
    So that method has to be invoked from a inside that fragment since access Bindings from xxxPageDef.xml
    I need to execute that code one and only one time when that fragment loads.
    What is the best approach to my case????

    Thanks Pino for your reply.
    Since the fragment does not have OnLoad event, I have no option than to find a work around.
    That is exactly what I am doing.
    I have a PageFlowScope variable which is set to true or false depending if I have input parameter value or not.
    That variable is re-sated when the user pressed a button.
    The problem was where to stick to code that will disable components if needed.
    So I used one component and in its Rendered method I put the code that will disable components if needed (based on my PageFlowScope variable value).
    Works perfectly fine, but it would be much nicer if there was more natural way of doing it (with OnLoad event on fragment).
    Regards.

  • Execute code from a text file ...

    Hello ,  Would like to know whether it is possible to have my ABAP code in a text file in desktop and then execute the code by reading it into an ITAB in another ABAP program .
    Note : Pl. dont suggest how to upload and create a new program . I dont want to create a new program after uploading into ITAB using INSERT or function modules . I want to execute the code as part of the uploading program only . So that once the execution is complete the uploaded code will not be available in the SAP system.
    Thanks in advance ,
    Jee.R

    >
    jeeva R wrote:
    > Note : Pl. dont suggest how to upload and create a new program . I dont want to create a new program after uploading into ITAB using INSERT or function modules . I want to execute the code as part of the uploading program only . So that once the execution is complete the uploaded code will not be available in the SAP system.
    Oh dear.  The only solution to your requirement is, sadly, to upload and create a new program, and then one further step.  There is no other way.  So it looks like you'll have to do without.
    matt

  • Event handlers execute code from a seperate class

    i am having difficulties linking my event handlers to another piece of code in a seperate class. basically i want my event handler to execute a code which is in another class. how do i do this?

    while adding listener to the component for which u want to handle event add listener with the name of class where u r going to write the event handling code and declare that class as implementing the type of listener and handle the event in that class by implementing the definitions for the methods in the interface

  • Removing TCP hex codes from ascii string

    I have a TCP connection to my VI and I'm using PuTTY to communicate with it. It is a basic terminal with a few commands. On boot my first command is always unrecognized because a few TCP protocol's are sent immediately beforehand:
    FF FB 1F “window size”
    FF FB 20 “terminal speed”
    FF FB 18 “terminal type”
    FF FB 27 “Telnet Environment Option”
    FF FD 01 “echo”
    FF FB 03 “suppress go ahead”
    FF FD 03 “suppress go ahead”
    Each command is always proceeded by a command character "FF". I can remove the entire offending sting without any problem, however what I've been trying to do is remove any hex code following the command character. I have tried a few things with regular expressions without much luck. Any insight on how to solve this challenge would be appreciated!
    Thanks,
    Devin 

    I'm not a regular expression power user, but I'd try something like the code below (right-click on "Search and Replace String" to set the "Regular Expression" option). This code looks for \FF followed by either \F0 through FA, or \FB through \FE followed by any other character, which I think matches the rules in the Telnet protocol as listed here: http://tools.ietf.org/html/rfc854 It replaces any match found with an empty string.

  • Error "Conversion failed when converting date and/or time from character string" to execute one query in sql 2008 r2, run ok in 2005.

    I have  a table-valued function that run in sql 2005 and when try to execute in sql 2008 r2, return the next "Conversion failed when converting date and/or time from character string".
    USE [Runtime]
    GO
    /****** Object:  UserDefinedFunction [dbo].[f_Pinto_Graf_P_Opt]    Script Date: 06/11/2013 08:47:47 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE   FUNCTION [dbo].[f_Pinto_Graf_P_Opt] (@fechaInicio datetime, @fechaFin datetime)  
    -- Declaramos la tabla "@Produc_Opt" que será devuelta por la funcion
    RETURNS @Produc_Opt table ( Hora datetime,NSACOS int, NSACOS_opt int)
    AS  
    BEGIN 
    -- Crea el Cursor
    DECLARE cursorHora CURSOR
    READ_ONLY
    FOR SELECT DateTime, Value FROM f_PP_Graficas ('Pinto_CON_SACOS',@fechaInicio, @fechaFin,'Pinto_PRODUCTO')
    -- Declaracion de variables locales
    DECLARE @produc_opt_hora int
    DECLARE @produc_opt_parc int
    DECLARE @nsacos int
    DECLARE @time_parc datetime
    -- Inicializamos VARIABLES
    SET @produc_opt_hora = (SELECT * FROM f_Valor (@fechaFin,'Pinto_PRODUC_OPT'))
    -- Abre y se crea el conjunto del cursor
    OPEN cursorHora
    -- Comenzamos los calculos 
    FETCH NEXT FROM cursorHora INTO @time_parc,@nsacos
    /************  BUCLE WHILE QUE SE VA A MOVER A TRAVES DEL CURSOR  ************/
    WHILE (@@fetch_status <> -1)
    BEGIN
    IF (@@fetch_status = -2)
    BEGIN
    -- Terminamos la ejecucion 
    BREAK
    END
    -- REALIZAMOS CÁLCULOS
    SET @produc_opt_parc = (SELECT dbo.f_P_Opt_Parc (@fechaInicio,@time_parc,@produc_opt_hora))
    -- INSERTAMOS VALORES EN LA TABLA
    INSERT @Produc_Opt VALUES (@time_parc,@nsacos, @produc_opt_parc)
    -- Avanzamos el cursor
    FETCH NEXT FROM cursorHora INTO @time_parc,@nsacos
    END
    /************  FIN DEL BUCLE QUE SE MUEVE A TRAVES DEL CURSOR  ***************/
    -- Cerramos el cursor
    CLOSE cursorHora
    -- Liberamos  los cursores
    DEALLOCATE cursorHora
    RETURN 
    END

    You can search the forums for that error message and find previous discussions - they all boil down to the same problem.  Somewhere in your query that calls this function, the code invoked implicitly converts from string to date/datetime.  In general,
    this works in any version of sql server if the runtime settings are correct for the format of the string data.  The fact that it works in one server and not in another server suggests that the query executes with different settings - and I'll assume for
    the moment that the format of the data involved in this conversion is consistent within the database/resultset and consistent between the 2 servers. 
    I suggest you read Tibor's guide to the datetime datatype (via the link to his site below) first - then go find the actual code that performs this conversion.  It may not be in the function you posted, since that function also executes other functions. 
    You also did not post the query that calls this function, so this function may not, in fact, be the source of the problem at all. 
    Tibor's site

  • Loading JavaFX code from string

    Hi,
    Here is my JavaFX code that I put to the SimplePainter.fx file:
    import javafx.stage.*;
    import javafx.scene.*;
    import javafx.scene.paint.*;
    import javafx.scene.input.*;
    import javafx.scene.shape.*;
    var elements: PathElement[];
    Stage {
        title: "Simple Painter"
        scene: Scene {
            content: Group{
                content: [
                    Rectangle{
                        width: 400
                        height: 300
                        fill: Color.WHITE
                        onMousePressed: function( e: MouseEvent ):Void {
                                insert MoveTo {x : e.x, y : e.y } into elements;
                        onMouseDragged: function( e: MouseEvent ):Void {
                                insert LineTo {x : e.x, y : e.y } into elements;
                    Path{
                        stroke: Color.BLUE
                        elements: bind elements
    }I am trying to use the ScriptEngineManager to evaluate the SimplePainter file:
    import java.io.FileReader;
    import javax.script.ScriptEngineManager;
    var path = "C:/Temp/fx/SimplePainter.fx";
    var manager = new ScriptEngineManager();
    var engine = manager.getEngineByExtension("fx");
    engine.eval(new FileReader(path));It throws AssertionError:
    java.lang.AssertionError
    at com.sun.tools.javac.jvm.Gen.visitBreak(Gen.java:1631)
    at com.sun.tools.javac.tree.JCTree$JCBreak.accept(JCTree.java:1167)
    at com.sun.tools.javac.jvm.Gen.genDef(Gen.java:679)
    at com.sun.tools.javac.jvm.Gen.genStat(Gen.java:714)
    However the simple 'println("Hello World!")' code is invoked fine.
    Do I do something wrong?
    Is it possible to use JavaFX compile methods to execute a JavaFX code from string?
    Thanks in advance.

    I experimented with that a while ago with JavaFX 1.1, with success: [Creating JavaFX Classes from Java Classes then running?|http://forums.sun.com/thread.jspa?threadID=5368159]
    I tried again:
    import java.io.*;
    import com.sun.javafx.api.JavaFXScriptEngine;
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    class RunJavaFXScript
      static String SCRIPT_NAME = "Test.fx";
      public static void main(String[] args)
        // Get the current directory
        File curDir = new File(".");
        // Get the script's file content
        BufferedReader reader = null;
        File fScript = new File(curDir.getAbsolutePath(), SCRIPT_NAME);
        System.out.println("Reading the " + fScript.getAbsolutePath() + " script");
        try
          reader = new BufferedReader(new FileReader(fScript));
        catch (FileNotFoundException e)
          System.err.println("File not found: " + fScript.getAbsolutePath());
          return;
        // Create a script on the fly
        String script = "function Demo() { println('Hello World!'); return 'It works!'; }";
        System.out.println("Getting the engines");
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByExtension("fx");
        System.out.println("Getting the generic ScriptEngine (by extension): " + engine);
        JavaFXScriptEngine fxEngine = (JavaFXScriptEngine) manager.getEngineByName("javafx");
        System.out.println("Getting the JavaFXScriptEngine: " + fxEngine);
        // Try to run it
        try
          System.out.println("Running the script read from a file: " + reader);
          Object readScript = engine.eval(reader);
          System.out.println("Running a built-in script");
          Object internalScript = fxEngine.eval(script);
          Object r = fxEngine.invokeFunction("Demo");
          System.out.println("Returned: " + (String) r);
        catch (Exception e)
          e.printStackTrace();
        finally
          try { reader.close(); } catch (IOException e) {}
    }Compiled with:
    javac -cp %JAVAFX_HOME%/lib/shared/javafxc.jar RunJavaFXScript.java(with JAVAFX_HOME pointing at javafx-sdk1.1)
    Ran with:
    java -cp %JAVAFX_HOME%/lib/shared/javafxc.jar;%JAVAFX_HOME%/lib/desktop/javafxgui.jar;%JAVAFX_HOME%/lib/desktop/Scenario.jar;. RunJavaFXScriptIt works:
    Reading the E:\Dev\PhiLhoSoft\Java\_QuickExperiments\.\Test.fx script
    Getting the engines
    Getting the generic ScriptEngine (by extension): com.sun.tools.javafx.script.JavaFXScriptEngineImpl@758fc9
    Getting the JavaFXScriptEngine: com.sun.tools.javafx.script.JavaFXScriptEngineImpl@1113708
    Running the script read from a file: java.io.BufferedReader@133f1d7
    Running a built-in script
    Hello World!
    Returned: It works!(and it shows a Stage with a small FX script showing an animation).
    Now, I try to do the same of JavaFX 1.2: same command line for compiling (except of course pointing to javafx-sdk1.2), run command is:
    java -cp . -Djava.ext.dirs=%JAVAFX_HOME%/lib/shared;%JAVAFX_HOME%/lib/desktop RunJavaFXScript(more jars to take in account, I take everything...)
    And when I run it I have:
    Reading the E:\Dev\PhiLhoSoft\Java\_QuickExperiments\.\Test.fx script
    Getting the engines
    Getting the generic ScriptEngine (by extension): com.sun.tools.javafx.script.JavaFXScriptEngineImpl@8813f2
    Getting the JavaFXScriptEngine: com.sun.tools.javafx.script.JavaFXScriptEngineImpl@1d58aae
    Running the script read from a file: java.io.BufferedReader@83cc67
    An exception has occurred in the OpenJavafx compiler. Please file a bug at the Openjfx-compiler issues home (https://openjfx-compiler.dev.java.net/Issues) after checking for duplicates. Include the following diagnostic in your report and, if possible, the source code which triggered this problem.  Thank you.
    java.lang.AssertionError
            at com.sun.tools.javac.jvm.Gen.visitBreak(Gen.java:1631)
            at com.sun.tools.javac.tree.JCTree$JCBreak.accept(JCTree.java:1167)
            at com.sun.tools.javac.jvm.Gen.genDef(Gen.java:679)
            at com.sun.tools.javac.jvm.Gen.genStat(Gen.java:714)
            at com.sun.tools.javac.jvm.Gen.genStat(Gen.java:700)
            at com.sun.tools.javac.jvm.Gen.genStats(Gen.java:751)
            at com.sun.tools.javac.jvm.Gen.genStats(Gen.java:735)
            at com.sun.tools.javac.jvm.Gen.visitSwitch(Gen.java:1210)
            at com.sun.tools.javac.tree.JCTree$JCSwitch.accept(JCTree.java:943)
            at com.sun.tools.javac.jvm.Gen.genDef(Gen.java:679)
            at com.sun.tools.javac.jvm.Gen.genStat(Gen.java:714)
            at com.sun.tools.javac.jvm.Gen.genStat(Gen.java:700)
            at com.sun.tools.javac.jvm.Gen.genLoop(Gen.java:1076)
            at com.sun.tools.javac.jvm.Gen.visitForLoop(Gen.java:1047)
            at com.sun.tools.javac.tree.JCTree$JCForLoop.accept(JCTree.java:856)
    (and so on)So I have the same issue.
    Looks like something have been broken in 1.2... :-(
    Of course, the tested scripts compile without problem.
    If I put only my simple built-in script in the Test.fx file, it works... I can put an empty Stage in the script (it is displayed), but if I add an empty Scene to it, I have the same error.

  • Executing jar from java code, then kill parent java code

    Please suggest if there is any best way around on executing jar from java code then killing parent java code.
    a) I have desktop based java application say "Monitor.java" which runs every 5 minutes.
    b) How can I START external java application say "execute.jar" from Monitor.java THEN EXIT Monitor.java
    I tried various options using "ProcessBuilder" and calling bat file but I need Monitor (parent application to EXIT, immediately after calling child (execute.jar)
    Try1) ProcessBuilder builder = new ProcessBuilder("java -jar execute.jar");          
    Process process = builder.start();
    Try2) Runtime r = Runtime.getRuntime();
    Process p = null;
    p = r.exec(new String[] { "cmd", "/c", "start C:/temp/Test.bat" });

    I have a requirement to transfer data from one db to another db from Java Application Layer.Maybe, maye not. We get all sorts of weird "requirements" - which are nothing but thoughts or proposed solutions.
    But,
    Did the "requirement" mention whether the table existed already or not in the target database? - If not, did it tell you to create it - drop/create it?
    Did the "requirement" deliver some explanation to why this copying was neeeded? - Are we talking replication? - Or a one time cloning?
    Etc, etc,
    Personally I would always argue against a "reuirement" like that. - It just isn't the way to do it. Period.
    Regards
    Peter
    P.S: If you are satisfied with what COPY does, then you could let Java make an OS call and do it from there?

  • Error: ORA-03113 while executing complex java code from Oracle PL/SQL

    Hi,
    I am trying to execute a complex java code from Oracle PL/SQL. The classes were resolved successfully. But in the middle of execution, I am getting the following error:
    ERROR:
    ORA-03114: not connected to ORACLE
    begin
    ERROR at line 1:
    ORA-03113: end-of-file on communication channel
    Process ID: 13685
    Session ID: 21 Serial number: 20
    Is there a way to debug the Java classes loaded into oracle? Or is there any utility to find out why the connection was lost?
    Regards,
    Saravana

    Hi Saravana:
    You could use simply System.out.println(..) at your Java code and see the output at the .trc files generated for your Oracle session.
    Or better than this adding Java Util Logging messages at your code, to see how to use JUL API at the OJVM please see this blog post [Using JUL API inside the OJVM|http://marceloochoa.blogspot.com/2007/11/getting-logging-entering-exiting-and.html].
    Best regards, Marcelo.
    PD: ora-0600 generally are associated with RDBMS bugs, but these bugs can be bypassed by replacing the code which throws the exception by other with a workaround.

  • Executing code in form of String object

    hi to all,
    I don't know if it's the right place to ask such a question, but at least, I can try my chance :)
    Can I execute code originally written in a text area (JTextArea) (i.e. in form of a String object) as if it was code already embedded in the code flow ??

    There are several solutions.
    As suggested above use Runtime.exec() to compile it. You can do this either by having the user enter the entire class or by having the enter only a portion which you then wrap (they write a method, or some rules in a method, etc.)
    There is a VM/version specific interface that allows you to compile without Runtime.exec() . You can search the site for examples of this.
    You can also use one of the java embeddable languages if you just what 'code' rather than supporting the entire java language.....search the following page for "Scripting"...
    http://flp.cs.tu-berlin.de/~tolk/vmlanguages.html

  • Exit codes from PowerBuilder executable in Redwood

    We are currently in the process of Integration Testing for SAP Go-Live planned for March 31, 2008.  Our Integration Testing is being done thru Redwood Job Scheduler.  There appears to be a problem with exit codes from our PowerBuilder executable that does not correlate to condition codes in Redwood.  The PowerBuilder executable either returns an exit code of 1 for successful or -1 for not successful.  Redwood interprets -1 as KILLED.  In reality the situation is that some records are processed successfully, but once a bad record is encountered, an exit code of -1 is set to indicate an error.  The question is - what can be done in Redwood to interpret PowerBuilder exit codes correctly?  In this case, we would expect an ERROR status to be produced but not a KILLED status which is misleading.

    This is much simple. Redwood is based on Oracle. You can get a help of oracle developer, you can handle this based on either exceptions or decode statement.
    Otherwise, you can write a job that gets triggered based on killed status of this job and checks the actual error in PB log file. Then it will change the status of this job to Error in database instead of Killed.
    - Bhushan

  • Execute Query from string

    Dear forum members,
    Is it possible to execute a query from a string like this:
    DECLARE
      thishere  VARCHAR2;
    BEGIN
      f:='from iv_view_cqir_sum where 1=1 ';
      select sum(a) into thishere [...];
    END;The [...] should be taken from the string f...
    Any comments welcome!
    Cheers,
    Johann

    You can do it in this way:
    SQL> create table test1(id number);
    Table created.
    SQL> insert into test1 values(1);
    1 row created.
    SQL> insert into test1 values(2);
    1 row created.
    SQL> DECLARE
       v_var     VARCHAR2 (10) := 'where id=1';
       v_count   NUMBER;
    BEGIN
       EXECUTE IMMEDIATE 'select count(1) from test1 ' || v_var
                    INTO v_count;
       DBMS_OUTPUT.put_line (v_count);
    END; 
    1- - - - - - - - - - - - - - - - - - - - -
    Kamran Agayev A. (10g OCP)
    http://kamranagayev.wordpress.com

  • Execute Javascript from our JAVA code

    Hi all,
    I have a question:
    It's possible to execute a javascript code from the back bean page. For example , we execute a button action (Conect to a db, insert data) and if all it's ok we execute a simple alert ("The insert is ok!!");
    Any way to do this??
    Thx!

    I don't know enough about Javascript, but I don't think it can be executed from within Java code.
    If you can't, an alternative is to provide a status code and/or status message that is accessible to the page. There are a number of ways to do this. One option is to put the information in a hidden field. Another option is to put the information in a session bean and add appropriate JSP code to your page to get that information.
    You can link a Javascript function to the page's onLoad event. The function can get the status code/status message and create the alert.

Maybe you are looking for

  • Switch active display between 2 monitors without click

    Hi, I'm using OS Mavericks with dual monitor setup (iMac with an external monitor) + each monitor has it's own spaces. I'm wondering if there is a way to instantly switch the active monitor (focus) to the other by just moving my mouse to that monitor

  • Restore/recover after failover to a Logical Standby database

    I have a question about how to recover or restore back to my original environment after I failover to my Logical Standby database. My setup is as follows: Oracle version 11.2.0.3, Non-RAC. 1. A Primary database at one location. 2. A Physical Standby

  • BusinessObjects XI 3.1 SP3 with tomcat6

    Hello How is it possible to install BusinessObjects XI 3.1 SP3 on a windows 2003 64bits platform with tomcat6? Thanks

  • Where to define new custom data type ?

    Hi, In the past (TS 3.5) I've created our own custom type palette file which has been used to store new data types and then passed the file to other colleagues. The file would be stored in the ......\Program Files\.......\User area. My question has a

  • IMovie-Problem with hangups.

    I just upgraded to IMovie 11 from IMovie 8. I only have about three short projects (15 min each) and one longer one (5 1/2 hours worth of clips) in IMovie, so it shouldn't be too slow. I had no problems with hangups working on 8, but immediately had