Esempio n. 1
0
  public String processInput(String input) {
    String output;
    boolean moreInputRequired;

    if (input == null) {
      // '\nHello {0}\nWelcome to the Ganymede Jython interpreter!\n\nType "quit" to exit.\n{1}'
      return ts.l("processInput.greeting", socket.getInetAddress().getHostAddress(), prompt);
    }

    if (input.equals(ts.l("processInput.quitcommand"))) {
      return doneString;
    }

    try {
      moreInputRequired = interp.push(input);
      if (moreInputRequired) {
        return "... ";
      }

      buffer.flush();
      output = buffer.toString();
      interp.resetbuffer();
      buffer.getBuffer().setLength(0);
    } catch (PyException pex) {
      output = buffer.toString() + "\n" + pex.toString();
      interp.resetbuffer();
      buffer.getBuffer().setLength(0);
    }

    return output + prompt;
  }
 protected synchronized void runMethod(String method) {
   try {
     this.exec(method + "()");
   } catch (PyException ex) {
     ex.printStackTrace();
     System.out.println("Error in filter spec " + ex.getMessage());
   }
 }
Esempio n. 3
0
 public PyObject __finditem__(int key) {
   PyType self_type = getType();
   PyObject impl = self_type.lookup("__getitem__");
   if (impl != null)
     try {
       return impl.__get__(this, self_type).__call__(new PyInteger(key));
     } catch (PyException exc) {
       if (exc.match(Py.LookupError)) return null;
       throw exc;
     }
   return super.__finditem__(key);
 }
 /** Called by the sax parser when the end of an element is encountered. */
 public void endElement(String namespaceURI, String local, String name) throws SAXException {
   if (name.equals(TagNames.CALLFLOW)) {
     //  Do an integrity check.
     // For every Expect node, there must be
     // a valid event template.
     try {
       callFlow.checkIntegrity();
     } catch (Exception ex) {
       System.out.println(ex.getMessage());
       ex.printStackTrace();
       throw new SAXException(ex.getMessage());
     }
   } else if (name.equals(TagNames.JYTHON_CODE)) {
     if (this.jythonCode != null) {
       JythonInterp jythonInterp = callFlow.getJythonInterp();
       try {
         jythonInterp.exec(this.jythonCode);
       } catch (PyException ex) {
         throw new SAXException(
             "error in evalScript \n" + this.jythonCode + "\n" + ex.getMessage());
       }
       this.jythonCode = null;
     }
   } else if (name.equals(TagNames.EXPECT)) {
     if (this.jythonCode != null) currentExpectNode.setJythonCode(this.jythonCode);
     this.jythonCode = null;
     callFlow.addExpectNode(currentExpectNode);
     currentExpectNode = null;
   } else if (name.equals(TagNames.SIP_REQUEST)) {
     if (this.messageTemplateContext) {
       MessageTemplate msgTemplate = new MessageTemplate(messageTemplate, id, this.jythonCode);
       callFlow.addMessageTemplate(msgTemplate);
       messageTemplate = null;
       this.jythonCode = null;
     }
   } else if (name.equals(TagNames.SIP_RESPONSE)) {
     if (this.messageTemplateContext) {
       MessageTemplate msgTemplate =
           new MessageTemplate(this.messageTemplate, this.id, this.jythonCode);
       callFlow.addMessageTemplate(msgTemplate);
       messageTemplate = null;
       this.jythonCode = null;
     }
   } else if (name.equals(TagNames.GENERATE)) {
     generateContext = false;
     if (generatedMessage.messageType.equals(Attr.SipRequest) && generatedMessage.method == null) {
       System.out.println("Current message node = " + generatedMessage.messageId);
       throw new SAXException("Missing method");
     }
   } else if (name.equals(TagNames.MESSAGE_TEMPLATES)) {
     messageTemplateContext = false;
   }
 }
Esempio n. 5
0
 public PyObject __iternext__() {
   PyType self_type = getType();
   PyObject impl = self_type.lookup("next");
   if (impl != null) {
     try {
       return impl.__get__(this, self_type).__call__();
     } catch (PyException exc) {
       if (exc.match(Py.StopIteration)) return null;
       throw exc;
     }
   }
   return super.__iternext__(); // ???
 }
Esempio n. 6
0
 /**
  * Returns the next element from an iterator. If it raises/throws StopIteration just store the
  * Exception and return null according to PyIterator practice.
  */
 protected PyObject nextElement(PyObject pyIter) {
   PyObject element = null;
   try {
     element = pyIter.__iternext__(); // next();
   } catch (PyException pyEx) {
     if (pyEx.match(Py.StopIteration)) {
       // store exception - will be used by PyIterator.next()
       stopException = pyEx;
     } else {
       throw pyEx;
     }
   }
   return element;
 }
 /** Evaluate a boolean expression. */
 protected synchronized boolean evalBoolean(String expression) {
   try {
     this.exec("retval = " + expression);
     PyObject pyObj = this.get("retval");
     String retString = pyObj.toString();
     Debug.println("retString = " + retString);
     if (retString.equals("1")) return true;
     else return false;
   } catch (PyException ex) {
     ex.printStackTrace();
     System.exit(0);
     return false;
   }
 }
 /**
  * Run this filter on the given SIP message (represented as an array canonical headers) and return
  * true or false.
  */
 protected synchronized boolean match(SIPMessage sipMsg) {
   this.set("sipMessage", sipMsg);
   try {
     this.exec("retval = match(sipMessage)");
     PyObject pyObj = this.get("retval");
     String retString = pyObj.toString();
     if (retString.equals("1")) return true;
     else return false;
   } catch (PyException ex) {
     ex.printStackTrace();
     System.out.println("Error in filter spec. " + ex.getMessage());
     System.exit(0);
   }
   return false;
 }
 @Override
 public PyObject __finditem__(PyObject key) { // ???
   PyType self_type = getType();
   PyObject impl = self_type.lookup("__getitem__");
   if (impl != null) {
     try {
       return impl.__get__(this, self_type).__call__(key);
     } catch (PyException exc) {
       if (exc.match(Py.LookupError)) {
         return null;
       }
       throw exc;
     }
   }
   return super.__finditem__(key);
 }
Esempio n. 10
0
 private static int py2int(PyObject obj, int defaultValue, String msg) {
   if (obj instanceof PyNone) {
     return defaultValue;
   } else {
     int value = defaultValue;
     try {
       value = Py.py2int(obj);
     } catch (PyException pyEx) {
       if (pyEx.match(Py.TypeError)) {
         throw Py.ValueError(msg);
       } else {
         throw pyEx;
       }
     }
     return value;
   }
 }
Esempio n. 11
0
 public void evalFile(String s) {
   for (String s2 : bindings.keySet()) {
     py.set(s2, bindings.get(s2));
   }
   py.setOut(getWriter());
   py.setErr(getErrorWriter());
   try {
     py.execfile(s);
     PyStringMap locals = (PyStringMap) py.getLocals();
     Object[] values = locals.values().toArray();
     Object[] keys = locals.keys().toArray();
     bindings.clear();
     for (int i = 0; i < keys.length; ++i) {
       bindings.put((String) keys[i], values[i]);
     }
   } catch (PyException pe) {
     getErrorWriter().write(pe.toString());
     getErrorWriter().flush();
   }
 }
 public PyObject __findattr_ex__(String name) {
   PyType self_type = getType();
   // TODO: We should speed this up. As the __getattribute__ slot almost never
   //       changes, it is a good candidate for caching, as PyClass does with
   //       __getattr__. See #1102.
   PyObject getattribute = self_type.lookup("__getattribute__");
   PyString py_name = null;
   PyException firstAttributeError = null;
   try {
     if (getattribute != null) {
       py_name = PyString.fromInterned(name);
       return getattribute.__get__(this, self_type).__call__(py_name);
     } else {
       Py.Warning(String.format("__getattribute__ not found on type %s", self_type.getName()));
       PyObject ret = super.__findattr_ex__(name);
       if (ret != null) {
         return ret;
       } // else: pass through to __getitem__ invocation
     }
   } catch (PyException e) {
     if (!e.match(Py.AttributeError)) {
       throw e;
     } else {
       firstAttributeError = e; // saved to avoid swallowing custom AttributeErrors
       // and pass through to __getattr__ invocation.
     }
   }
   PyObject getattr = self_type.lookup("__getattr__");
   if (getattr != null) {
     if (py_name == null) {
       py_name = PyString.fromInterned(name);
     }
     return getattr.__get__(this, self_type).__call__(py_name);
   }
   if (firstAttributeError != null) {
     throw firstAttributeError;
   }
   return null;
 }
  @Override
  public boolean sendLine(String command, Consumer<String> callback) {
    if (interactiveInterpreter == null) {
      try {
        interactiveInterpreter =
            jythonJythonInterpreterFactory.createInstance(InteractiveInterpreter.class);
        interactiveInterpreter.setOut(returnBuffer);
        interactiveInterpreter.setErr(returnBuffer);
      } catch (PlayOnLinuxException e) {
        LOGGER.error(e);
      }
    }

    commandBuffer.append(command);

    if (command.startsWith("\t") || command.startsWith(" ") || command.trim().endsWith(":")) {
      commandBuffer.append("\n");
      callback.accept("");
      return false;
    } else {
      String completeCommand = commandBuffer.toString();
      commandBuffer.setLength(0);
      currentTask =
          executorService.submit(
              () -> {
                returnBuffer.getBuffer().setLength(0);
                try {
                  interactiveInterpreter.exec(completeCommand);
                  callback.accept(returnBuffer.toString());
                } catch (PyException e) {
                  LOGGER.debug(e);
                  callback.accept(e.toString());
                }
              });
      return true;
    }
  }