KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > neu > ccs > jmk > shell > JPython


1 // $Id: JPython.java,v 1.2 2001/12/07 11:41:24 ramsdell Exp $
2

3 // The implementation of the JPython operator.
4

5 /*
6  * Copyright 1998 by John D. Ramsdell
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */

22
23 package edu.neu.ccs.jmk.shell;
24
25 import org.python.util.PythonInterpreter;
26 import org.python.core.PyException;
27 import edu.neu.ccs.jmk.Operator;
28 import edu.neu.ccs.jmk.CommandFailedException;
29
30 /**
31  * JPython as an Operator.
32  * <pre>
33  * python = "edu.neu.ccs.jmk.shell.JPython";
34  *
35  * "all":;
36  * {
37  * forname python "1 + 4";
38  * }
39  * </pre>
40  */

41 public class JPython
42 implements Operator
43 {
44   public String JavaDoc getName() {
45     return "JPython";
46   }
47
48   /**
49    * Execute the operation by concatenating the arguments
50    * and executing the string using JPython.
51    * @param args parameters to the operation
52    * @param out place to write messages
53    * @exception CommandFailedException if operation failed
54    */

55   public void exec(String JavaDoc[] args, java.io.PrintWriter JavaDoc out)
56        throws CommandFailedException
57   {
58     if (args.length == 0)
59       throw new CommandFailedException("No args to " + getName());
60     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(args[0]);
61     for (int i = 1; i < args.length; i++)
62       sb.append(args[i]);
63     PythonInterpreter pi = new PythonInterpreter();
64     try {
65       pi.exec(sb.toString());
66     }
67     catch (PyException pex) {
68       out.println(pex);
69       throw new CommandFailedException(getName() + " threw an exception");
70     }
71   }
72 }
73
Popular Tags