The combination of Java and Jython

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.

分类:Java 时间:2010-04-30 人气:421
分享到:
blog comments powered by Disqus

相关文章

  • Python scripting language is very useful 2010-12-25

    Python scripting language ---------------- very useful Today, do not know which nerve short-circuit, even started to pay attention Python. Internet casually looked down a document, think this thing is too practical it! Might be possible to carefully

  • Faramita draft language design 0.1 - truly mobile code (mobile code) 2010-04-19

    Faramita draft language design 0.1 Advertising language (not really): The real mobile code (mobile code), a real distributed computing Abbreviation explanation: RPC: Remote Procedure Call Remote Call DSL: Domain Specific Language Domain Specific Lang

  • JDK6 new features: Scripting language support (Scripting) 2010-03-29

    Overview JDK6 increased its support for scripting languages (JSR 223), theory is the scripting language to compile into bytecode, so scripting languages can also enjoy the Java platform, many advantages, including portability, safety, etc. In additio

  • What is a compiled language. Explanatory language and scripting language 2010-03-12

    The computer can not directly understand the high-level language, can only understand machine language directly, it must be high-level language should be translated into machine language, the computer can be value-based high-level language program. T

  • LUA scripting language entry 2010-03-28

    LUA scripting language entry Preliminary Study Lua Programming: Mu Feng (Second Life members) This article comes from CSDN blog: http://blog.csdn.net/skyremember/archive/2008/10/17/3089447.aspx In this article, I want to tell you how to Lua programmi

  • How effectively prevent the Java program source code was peeping? 2010-06-28

    Java program's source code is easy for people to peep, as long as an anti-compiler, any person can analyze other people's code. This article discusses how to modify the original program without the case, through encryption technology to protect the s

  • [Jia Wen Dramas] kernel read from the java performance analysis and design 2010-08-20

    Transfer from: http://blog.csdn.net/chief1985/archive/2008/03/21/2201392.aspx Introduction java since the emergence of language from the 90's, because of its safety and cross-platform (ie the so-called "Write Once, Run Anywhere") and so on, won

  • The second java program - drawing board 2010-11-27

    I. Features: 1. To achieve draw lines, circles, rectangles, four rubber shapes. Drawing mode: hold down the mouse button drag, and then released, and Windows, similar to the way drawing; 2. Can select pen color; 3. According to the user to specify th

  • C-based scripting language development technology-csp 2011-05-01

    What is eybuild http://www.eybuild.com/develop/index.htm eyBuild, is short for Easy Build, which is the CSP (C Language Service Page) development kit in general. eyBuild WEB applications on embedded devices is the ideal development tool, with a WEB s

  • OutOfMemory java program based on problem solving and Xms / Xmx / Xss interpretation and application of 2010-02-24

    Has long been doing java application development, using development tools basically are based on java, and often have eclipse, netbeans, ant, maven, cruisecontrol, tomcat, findbugs so. When using these tools, sometimes encounter OutOfMemory problem.

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.570 (s). 12 q(s)