The combination of Java and Jython

sponsored links
Recently re-designed a program, this program has a function to monitor the memory usage of other processes, and in certain conditions when the trigger warnings to the user. General conditions, the memory more than a certain threshold. However, this condition can be complicated if you want more, for example, when more than 2G and sustained increase of 2 days, the alarm; or if less than 1G, and the overall trend within 10 days of growth, but also alarm. In short, this condition can support very complex conditions, and the need for dynamic modifications (the main module does not restart the case), so my choice is a combination of Java and Jython. In fact, the choice of Java above JRuby, Scala, Groovy or Javascript, Jython choice of the following reasons:

[1] units of a number of projects have used the Python;

[2] Scala and Groovy will be too little, too avant-garde of the;

[3] Javascript very well, but taking into account all the Java program may be expanded in the future will use a scripting language, interactive system capacity significantly Javascript bad. For example, link databases, processing of documents ah

[4] Ruby is too hard to let go of me, because I like Ruby, Ruby Enterprise Edition has in fact relatively stable, and JRuby also has official support. Only unit in the project have been used in Python, if the temerity of the introduction of Ruby, is bound to increase the system's complexity.

[5] Even if there JPerl, JTcl, I will not use. The reason is simple, I need a better modular object-oriented scripting, object-oriented is not a silver bullet, but we are familiar with object-oriented, and it proved to encourage everyone to write good object-oriented maintenance code (combined with design mode).

[6] C + + and Python can be integrated (Boost.Python) (of course, Lua easier integration with C + +, Lua, but too few people will).

[7] can use Java to write, and then use reflection, you can do. But I think the script better, and to cut the compilation process. (Because in the field, can not guarantee that your Unix installed above the JDK, can only guarantee a JRE).

[8] using Java5, not Java6, so JSR233 (as is the bar) can not directly use.

Because this project is a unit of the project, so I do Prestudy my little program out and share on a solution.

I always like to use the calculator to do this small example PreStudy, Oh.

First, the interface design a calculator ICalc (written with Java), as follows:

package com.gmail.at.ankyhe.calc;

public interface ICalc {
        void pushData(int[] data);
        int getResult();
}
package com.gmail.at.ankyhe.calc;

public interface ICalc {
        void pushData(int[] data);
        int getResult();
}


Obviously, this interface which has two functions. The first function is pushData, the main module calls this function to the data sent to specific Calc class (to achieve this using Jython), and then through the getResult () get the results, thinking is very simple. In order to dynamically update the files found, we send data to Calc and Calc are the results from the task into a separate thread inside, as follows:

package com.gmail.at.ankyhe.calc;

import java.util.Arrays;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class CalcTask implements Runnable {

        public CalcTask(ICalc aCalc) {
                calc = aCalc;
                rand = new Random((new Date()).getTime());
                arr = new int[3];
        }
        
        public ICalc setCalc(ICalc aCalc) {
        ICalc tmp = calc; 
          synchronized(this) {
          calc = aCalc;
          }
        return tmp;
        }

        public void run() {
                while (true) {
                        for(int i = 0 ; i < arr.length; ++i) {
                                arr[i] = rand.nextInt() % 50;
                        }
                        int rst = 0;
                        synchronized (this) {
                          calc.pushData(arr);
                          rst = calc.getResult();
      }
                        System.out.println(String.format("Input: %s --- Output: %d", 
                                                                Arrays.toString(arr), rst));
                        try {
                                TimeUnit.SECONDS.sleep(50);
                        } catch (InterruptedException ex) {
                                ex.printStackTrace();
                        }
                }
        }

        private ICalc calc;
        private Random rand;
        private int[] arr;
}


Then the main thread which is responsible for scanning Jython script and load it as follows:

package com.gmail.at.ankyhe.calc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.python.util.PythonInterpreter;


public class Main {
        
        public static ICalc getCalc() {
                Reader file = null;
                file = null;
                try {
                        file = new FileReader(filename);
                } catch(FileNotFoundException ex) {
                        System.out.println("Can't find the file.");
                        System.exit(1);
                }
                try {
        Reader in = new BufferedReader(file);
                        PythonInterpreter interpreter = new PythonInterpreter();
                        org.python.core.PyObject code = interpreter.compile(in);
                        interpreter.exec(code);
                        ICalc calc = (ICalc)interpreter.get("calc", ICalc.class);
                        return calc;
                } finally {
                        try {
                                file.close();
                        } catch(IOException ex) {
                                System.out.print("Fail to close file");
                                System.exit(1);
                        }
                }
        }
        
        public static long getLastModified() {
          long rst = 0L;
                File f = null;
                try {
                        f = new File(filename);
                        rst = f.lastModified();
                } catch(NullPointerException ex) {
                        ex.printStackTrace();
                        rst = -1; 
                }
                return rst;
        }

        public static void main(String[] args) throws InterruptedException {
          // initialization
          if (args.length == 0) {
            System.out.println("Usage java -jar calc.jar <scriptfile>.");
            System.exit(1);
          }
          
          filename = args[0];
                ICalc calc = null;
                if (lastmodified == 0) {
                        lastmodified = getLastModified();
                        if (lastmodified == -1) {
        System.out
            .println(String.format("The file %s doesn't exit.", filename));
                        }
                        calc = getCalc();
                }
                if(calc == null) {
      System.out.print(String.format("The script file has no valid calc.",
          filename));
                        System.exit(2);
                }
                
                // launch calc task
                CalcTask ct = new CalcTask(calc);
                ExecutorService es = Executors.newCachedThreadPool();
                es.execute(ct);
                es.shutdown();
                
                // main thread check the new script every 10 seconds
                while(true) {
                        long modified = getLastModified();
                        if (modified <= lastmodified) {
                          // do nothing 
                        }
                        else {
                          lastmodified = getLastModified(); 
                          ICalc newCalc = getCalc();
                          if (newCalc == null) {
                            System.out.print(String.format("The new script file has no valid calc.", 
                                filename));
                          }
                          else {
                            System.out.println("Ready to use new script file.");
                            ct.setCalc(newCalc); 
                            System.out.println("Use new script file.");
                          }
                        }
                        TimeUnit.SECONDS.sleep(10);
                }
        }
        
        public static String filename = null;
        public static long lastmodified = 0;

}


Loading of the core code is the following paragraph:

PythonInterpreter interpreter = new PythonInterpreter();
org.python.core.PyObject code = interpreter.compile(in);
interpreter.exec(code);
ICalc calc = (ICalc)interpreter.get("calc", ICalc.class);


Note that in the Jython script must be a ICalc calc subclass object, or the last sentence of the above will throw an exception. Jython code:

import sys
# add sys path
def addSysPath():
  sys.path.append("/Users/AnkyHe/proj/java/CalcPlugin/icalc.jar")

addSysPath()

from com.gmail.at.ankyhe.calc import ICalc

class MyCalc(ICalc):
  def __init__(self):
    pass
  def pushData(self, arr):
    self.arr = arr
  def getResult(self):
    return sum(self.arr)
    #return min(self.arr)

calc = MyCalc()

'''
if __name__ == '__main__':
  mycalc = MyCalc()
  arr = [1, -100, 20]
  mycalc.pushData(arr)
  if sum(arr) == mycalc.getResult():
    print('true')
  else:
    print('false')
    print(mycalc.getResult())
'''

sys.path.append is to interface to ICalc the jar file to use Jython environment, it can import ICalc. Note the last if __name__ == '__main__', here shows an advantage of using Jython, you can do Jython test. It is only a Presutdy, the main task is to test the process, so there might be some error handling is not written very comprehensive. Source code and executable file (compiled to run on my Mac via a) If the attachment, execution time, please use:

java-cp. / icalc.jar-jar calcplugin.jar script / mycalc.py

Compile time using the icalc.jar and jython.jar added to the classpath in the.

Then you modify mycalc.py, you can see the output change.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of The combination of Java and Jython

  • Java Design Pattern Part of the abstract factory pattern

    Abstract factory pattern is an abstract factory pattern than an even higher degree of model. In short, the abstract factory class and the factory class of the same principle, only factory class is back in the general category and examples; and return the

  • Designed with the real coding

    Software development process at the design and coding, both organizations (as well as other details of the project controllability requirements) engineering method is XP ah, UPS ah what the design phase is to cover the entire software development pro ...

  • J2EEer Learn Ruby

    Ruby has long heard of the development of efficient and accurate is to use Ruby on Rails to develop WEB applications very convenient. While J2EE has a lot of very good Opensource framework, automatic code generation tools, can greatly enhance the developm

  • Spring and Hibernate Integration

    1. Management SessionFactory Spring Integration to use Hibernate, we do not need to file hibernate.cfg.xml. First, in the applicationContext.xml to configure the data source (dataSource) bean and the session factory (sessionFactory) bean. Among them, the

  • The real design and coding

    Software development process at the design and coding, both organizations (as well as other details of the project controllability requirements) engineering method is XP ah, UPS ah what the design phase is to cover the entire software development pro ...

  • Talk about the "design mode"

    Now more and more frameworks; model appears to reduce the use of the opportunity, then mean that we do not have to grasp the mode of the case? In fact, in order to study the actual training model mode of thinking, modes of thinking help to understand ...

  • Ruby Symbol

    Ruby is a completely cross-platform object-oriented scripting language, built on the Ruby-based Web framework Ruby on Rails (ROR) is the field of web development is gaining increasing acceptance. ROR substantial use of the Ruby language features, Symbol i

  • jdbc even ORACLE, SQLServer2000, mysql ways

    According to other people say can make a ride to one of the clear step by step, not as easy to write your own ideas! 1. Even the oracle The direct use of the oracle are provided give a jar package jdbc: oracle alone is installed, and 10g of oracle on ...

  • flash chart summary

    pen Flash Chart is an open source Flash chart drawing tool, offers a variety of programming interfaces, including PHP, Ruby, Perl, Python, Java,. Net, AS, JS, etc. to generate a variety of data interfaces, and then Flash to display the function is to ...

  • spring myfaces hibernate richfaces

    1.web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries