Package anvil.script

Source Code of anvil.script.Context

/*
* $Id: Context.java,v 1.102 2002/09/16 08:05:03 jkl Exp $
*
* Copyright (c) 2002 Njet Communications Ltd. All Rights Reserved.
*
* Use is subject to license terms, as defined in
* Anvil Sofware License, Version 1.1. See LICENSE
* file, or http://njet.org/license-1.1.txt
*/
package anvil.script;

import anvil.Log;
import anvil.ErrorListener;
import anvil.core.Any;
import anvil.core.Any.Op;
import anvil.core.AnyList;
import anvil.core.AnyString;
import anvil.core.AnyClass;
import anvil.core.Array;
import anvil.core.ObjectPool;
import anvil.core.AnyThrowable;
import anvil.core.Modules;
import anvil.core.runtime.AnyFunction;
import anvil.core.runtime.AnyNamespace;
import anvil.core.runtime.AnyScope;
import anvil.core.runtime.AnyStackTraceElement;
import anvil.core.reflect.Reflection;
import anvil.core.Register;
import anvil.ErrorEvent;
import anvil.ErrorListener;
import anvil.ErrorListenerImpl;
import anvil.ForgingException;
import anvil.Location;
import anvil.server.Citizen;
import anvil.server.Zone;
import anvil.server.Address;
import anvil.server.Server;
import anvil.server.LocalizationPreferences;
import anvil.java.util.BindingEnumeration;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Stack;
import java.util.TimeZone;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.security.Permission;
import java.security.PermissionCollection;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Perl5Matcher;
import org.apache.oro.text.regex.Pattern;
import anvil.core.Throwables;

public final class Context extends StackFrameStack
implements Namespace
{

  public static final byte[] NEWLINE = new byte[] { (byte)'\n' };
 
  public static final String GLOBAL = "global";
  public static final String MODULE = "module";
 
  public static final NamespaceType TYPE = new NamespaceType()
  {
 
    public String getName()
    {
      return GLOBAL;
    }

    public String getQualifiedName()
    {
      return GLOBAL;
    }

    public int getType()
    {
      return Type.GLOBAL_NAMESPACE;
    }
   
    public Scope getParent()
    {
      return null;
    }

    public anvil.doc.Doc getDocument()
    {
      return null;
    }

    public int getTypeRef(anvil.codec.ConstantPool pool)
    {
      return 0;
    }

    public Namespace getNamespace()
    {
      return null;
    }
   
  };
 
  private Zone         _zone;
  private boolean      _hasPolicy = false;
  private Citizen      _citizen;
  private Thread       _thread;
  private Modules      _modules;
  private Namespace    _globals;
  private OutputStream _output = null;
  private Stack        _outputStack = new Stack();
  private Locale       _locale;
  private String       _language;
  private TimeZone     _timezone;
  private AnyNamespace _global;

  private static WeakHashMap _context = new WeakHashMap();

 
  public static final Context getInstance()
  {
    synchronized(_context) {
      Stack stack = (Stack)_context.get(Thread.currentThread());
      if (stack == null || stack.isEmpty()) {
        throw new RuntimeException("Context is missing for thread: " + Thread.currentThread());
      }
      return (Context)stack.peek();
    }
  }
 
 
  public static final void dumpStacks(PrintStream out)
  {
    synchronized(_context) {
      Iterator iter = _context.entrySet().iterator();
      while(iter.hasNext()) {
        Map.Entry entry = (Map.Entry)iter.next();
        Thread thread = (Thread)entry.getKey();
        Stack stack = (Stack)entry.getValue();
        out.println("----------- "+thread+" ---------");
        if (stack != null) {
          int i = stack.size() - 1;
          while(i >= 0) {
            Context ctx = (Context)stack.get(i);
            if (ctx != null) {
              int j = ctx.size() - 1;
              while(j>=0) {
                StackFrame frame = ctx.peek(j--);
                if (frame != null) {
                  Function function = frame.getFunction();
                  String path = frame.getPathinfo();
                  if (function != null && path != null) {
                    out.print(function);
                    out.print("  [");
                    out.print(path);
                    int line = frame.getLine();
                    if (line > 0) {
                      out.print(": ");
                      out.print(line);
                    }
                    out.println("]");
                  }
                }
              }
              out.println();
            }
            i--;
          }
          out.println();
        }
      }
    }
  }
 
 
  public static final Context getExistingInstance()
  {
    synchronized(_context) {
      Stack stack = (Stack)_context.get(Thread.currentThread());
      if (stack == null || stack.isEmpty()) {
        return null;
      } else {
        return (Context)stack.peek();
      }
    }
  } 
 
 
  public static final Context getInstance(Zone zone)
  {
    synchronized(_context) {
      Thread thread = Thread.currentThread();
      Stack stack = (Stack)_context.get(thread);
      if (stack == null || stack.isEmpty()) {
        Context context = new Context(zone);
        putInstance(thread, context);
        return context;
      }
      return (Context)stack.peek();
    }
  }



  public static final Context getInstance(Thread thread)
  {
    synchronized(_context) {
      Stack stack = (Stack)_context.get(thread);
      if (stack == null || stack.isEmpty()) {
        throw new RuntimeException("Context is missing for thread: " + thread);
      }
      return (Context)stack.peek();
    }
  }
 
 
  public static final void putInstance(Thread thread, Context context)
  {
    synchronized(_context) {
      Stack stack = (Stack)_context.get(thread);
      if (stack == null) {
        _context.put(thread, stack = new Stack());
      }
      stack.push(context);
    }
  }


  public static final void destroyInstance(Thread thread)
  {
    synchronized(_context) {
      Stack stack = (Stack)_context.get(thread);
      if (stack != null && !stack.isEmpty()) {
        Context ctx = (Context)stack.pop();
      }
    }
  }
 
 
  public Context(Zone zone)
  {
    this(Thread.currentThread(), zone, null, new NamespaceImpl());
  }

 
  public Context(Thread thread, Zone zone, Citizen citizen, Namespace globals)
  {
    _thread  = thread;
    _zone    = zone;
    _hasPolicy = zone.getDomain().hasPolicy();
    if (citizen != null) {
      if (citizen.getCombinedPermissions() != null) {
        _hasPolicy = true;
      }
    }
    _citizen = citizen;
    _modules = zone.getModules();
    _globals = globals;
    _global  = new AnyNamespace(this);
    LocalizationPreferences prefs = zone.getLocalizationPreferences();
    _language   = prefs.getLanguage();
    _locale     = prefs.getLocaleInstance();
    _timezone   = prefs.getTimezoneInstance();
    if (thread != null) {
      putInstance(thread, this);
    }
  }


  public final void join(Thread thread)
  {
    putInstance(thread, this);
  }
 
 
  public final Context copy(Thread thread)
  {
    Context ctx = new Context(thread, _zone, _citizen, new NamespaceImpl());
    ctx._locale     = _locale;
    ctx._language   = _language;
    ctx._timezone   = _timezone;
    return ctx;
  }
   
   
  public void destroy()
  {
    destroyInstance(_thread);
    _zone = null;
    _thread = null;
    _modules = null;
    _globals = null;
    _output = null;
    _outputStack.clear();
    _outputStack = null;
    _locale = null;
    _language = null;
    _timezone = null;
    _global = null;
  }
   
 
  public final Modules getModules()
  {
    return _modules;
  }
 

  /* exceptions */

 
  public final Location getCurrentLocation()
  {
    return new Location(address().getURL(), _frame.getLine(), 0);
  }
 
 
  public final AnyList getStackTrace()
  {
    int n = size();
    Any[] trace = new Any[n];
    int c = 0;
    for(int i = n-1; i >= 0; i--) {
      trace[c++] = new AnyStackTraceElement(peek(i));
    }
    return new AnyList(trace);
  }


  public final ScriptException exception(Any data)
  {
    return new ScriptException(data);
  }
 
 
  /* stack frame */

  public final StackFrame frame()
  {
    return _frame;
  }
 
 
  public final Function function()
  {
    return _frame.getFunction();
  }


  public final Module script()
  {
    return _frame.getModule();
  }


  public final Address address()
  {
    if (_frame == null) {
      return _zone.getAddress();
    }
    return _frame.getModule().getAddress();
  }


  public final Zone zone()
  {
    if (_frame == null) {
      return _zone;
    }
    return _frame.getZone();
  }


  public final Log log()
  {
    if (_frame == null) {
      return _zone.log();
    }
    return _frame.getZone().log();
  }
 
  /* security */

  public boolean checkPermission(Permission perm)
  {
    Log log = log();
    if (log.getSeverity() >= Log.DEBUG) {
      log.debug(perm.toString());
    }
 
    Citizen citizen = _citizen;
    if (citizen != null) {
      PermissionCollection pc = citizen.getCombinedPermissions();
      if (pc != null) {
        if (pc.implies(perm)) {
          return true;
        }
      }
    }
   
    int n = size();
    Zone[] zones = new Zone[n];
    int c = 0;
   
  alreadyChecked:
    for(int i=n-1; i>=0; i--) {
      Zone zone = peek(i).getZone();
      for(int j=0; j<c; j++) {
        if (zones[j] == zone) {
          continue alreadyChecked;
        }
      }
      if (zone.checkPermission(perm)) {
        return true;
      }
      zones[c++] = zone;
    }
   
    return false;
  }


  public void checkAcquire(String poolname)
    throws anvil.database.CannotReturnPooledConnectionException
  {
    if (_hasPolicy) {
      if (!checkPermission(new anvil.database.ConnectionPoolPermission(poolname))) {
        throw new anvil.database.CannotReturnPooledConnectionException("Access denied: "+poolname);
      }
    }
  }
 
  public void checkRealm(String name)
  {
    if (_hasPolicy) {
      if (!checkPermission(new anvil.server.RealmPermission(name))) {
        throw AccessDenied("Cannot access realm: "+name);
      }
    }
  }
   
  public void checkNamespace(String namespace, boolean writable)
  {
    if (_hasPolicy) {
      if (!checkPermission(new anvil.server.NamespacePermission(namespace, writable))) {
        if (writable) {
          throw AccessDenied("Cannot modify namespace: "+namespace);
        } else {
          throw AccessDenied("Cannot access namespace: "+namespace);
        }
      }
    }
  }
 

  public void checkAccess(String resource)
  {
    if (_hasPolicy) {
      if (!checkPermission(new anvil.core.RuntimePermission(resource))) {
        throw AccessDenied("Cannot access: "+resource);
      }
    }
  }   
 
  public void checkAccess(String resource, boolean writable)
  {
    if (_hasPolicy) {
      if (!checkPermission(new anvil.core.RuntimePermission(resource, writable))) {
        if (writable) {
          throw AccessDenied("Cannot modify: "+resource);
        } else {
          throw AccessDenied("Cannot access: "+resource);
        }
      }
    }
  }   
 
 
  public void checkAccess(anvil.core.RuntimePermission perm)
  {
    if (_hasPolicy) {
      if (!checkPermission(perm)) {
        if (perm.isWritable()) {
          throw AccessDenied("Cannot modify: "+perm.getName());
        } else {
          throw AccessDenied("Cannot access: "+perm.getName());
        }
      }
    }
  }   
 

  public void checkReflection(String classname)
  {
    if (_hasPolicy) {
      if (!checkPermission(new anvil.java.security.JavaPermission(classname))) {
        throw AccessDenied("Cannot access java: "+classname);
      }
    }
  } 


  public void checkImport(String target)
  {
    checkImport(frame().getPathinfo(), target);
  }
 

  public void checkImport(String source, String target)
  {
    if (_hasPolicy) {
      if (ImportPermission.onSameDir(source, target)) {
        return;
      }
      if (!checkPermission(new ImportPermission(target))) {
        throw AccessDenied("Cannot import: "+target);
      }
    }
  } 
 

  private static java.net.SocketPermission _localListenPermission = null;

  public void checkListen(int port)
  {
    if (_hasPolicy) {
      if (port == 0) {
        if (_localListenPermission == null) {
          _localListenPermission = new java.net.SocketPermission("localhost:1024-","listen");
        }
        if (!checkPermission(_localListenPermission)) {
          throw AccessDenied( "Cannot listen: localhost:1024-");
        }
      } else {
        if (!checkPermission(new java.net.SocketPermission("localhost:"+port, "listen"))) {
          throw AccessDenied("Cannot listen: localhost:" + port);
        }
      }
    }
  } 

  public void checkAccept(String host, int port)
  {
    if (_hasPolicy) {
      if (!checkPermission(new java.net.SocketPermission(host + ':' + port, "accept"))) {
        throw AccessDenied("Cannot accept: " + host + ':' + port);
      }
    }
  } 


  public void checkConnect(String host, int port)
  {
    if (_hasPolicy) {
      if (port == -1) {
        if (!checkPermission(new java.net.SocketPermission(host, "resolve"))) {
          throw AccessDenied("Cannot resolve: " + host);
        }
      } else {
        if (!checkPermission(new java.net.SocketPermission(host + ':' + port, "connect"))) {
          throw AccessDenied("Cannot connect: " + host + ':' + port);
        }
      }
    }
  } 


  public void checkRead(String path)
  {
    if (_hasPolicy) {
      if (!checkPermission(new java.io.FilePermission(path, "read"))) {
        throw AccessDenied("Cannot read: "+path);
      }
    }
  }
 

  public void checkWrite(String path)
  {
    if (_hasPolicy) {
      if (!checkPermission(new java.io.FilePermission(path, "write"))) {
        throw AccessDenied("Cannot write: "+path);
      }
    }
  } 
 

  public void checkDelete(String path)
  {
    if (_hasPolicy) {
      if (!checkPermission(new java.io.FilePermission(path, "delete"))) {
        throw AccessDenied("Cannot delete: "+path);
      }
    }
  } 
 

  public void checkExec(String path)
  {
    if (_hasPolicy) {
      if (!checkPermission(new java.io.FilePermission(path, "exec"))) {
        throw AccessDenied("Cannot execute: "+path);
      }
    }
  } 
   

  /* namespaces */


  public Any global()
  {
    return _global;
  }


  public String getName()
  {
    return "global";
  }
 

  public Any getNS(String name)
  {
    if (name == GLOBAL || name.equals(GLOBAL)) {
      return new AnyNamespace(this);
    }
    checkNamespace(name, false);
    Namespace ns = zone().getNamespace(name);
    return (ns != null) ? new AnyNamespace(ns) : Any.UNDEFINED;
  }


  public final BindingEnumeration getVariables()
  {
    return _globals.getVariables();
 
 
 
  public final Any getVariable(String name)
  {
    return _globals.getVariable(name);
  }


  public final Any setVariable(String name, Any value)
  {
    return _globals.setVariable(name, value);
  }
 
 
  public final Any checkVariable(String name)
  {
    return _globals.checkVariable(name);
  }
 
 
  public final boolean deleteVariable(String name)
  {
    return _globals.deleteVariable(name);
  }
   

  public final Any exec(Function function, StackFrame escape, Any[] parameters)
  {
    _escape = escape;
    return function.execute(this, null, parameters);
  }

  public final Any exec(Function function, StackFrame escape)
  {
    _escape = escape;
    return function.execute(this, (Any)null);
  }

  public final Any exec(Function function, StackFrame escape, Any param1)
  {
    _escape = escape;
    return function.execute(this, null, param1);
  }

  public final Any exec(Function function, StackFrame escape, Any param1, Any param2)
  {
    _escape = escape;
    return function.execute(this, null, param1, param2);
  }

  public final Any exec(Function function, StackFrame escape, Any param1, Any param2, Any param3)
  {
    _escape = escape;
    return function.execute(this, null, param1, param2, param3);
  }

  public final Any exec(Function function, StackFrame escape, Any param1, Any param2, Any param3, Any param4)
  {
    _escape = escape;
    return function.execute(this, null, param1, param2, param3, param4);
  }


  public final Any exec(Any self, Function function, StackFrame escape, Any[] parameters)
  {
    _escape = escape;
    return function.execute(this, self, parameters);
  }

  public final Any exec(Any self, Function function, StackFrame escape)
  {
    _escape = escape;
    return function.execute(this, self);
  }

  public final Any exec(Any self, Function function, StackFrame escape, Any param1)
  {
    _escape = escape;
    return function.execute(this, self, param1);
  }

  public final Any exec(Any self, Function function, StackFrame escape, Any param1, Any param2)
  {
    _escape = escape;
    return function.execute(this, self, param1, param2);
  }

  public final Any exec(Any self, Function function, StackFrame escape, Any param1, Any param2, Any param3)
  {
    _escape = escape;
    return function.execute(this, self, param1, param2, param3);
  }

  public final Any exec(Any self, Function function, StackFrame escape, Any param1, Any param2, Any param3, Any param4)
  {
    _escape = escape;
    return function.execute(this, self, param1, param2, param3, param4);
  }


  /* external entry point to context */
 

  public final Any execute(Module script, String name, Any[] parameters) throws ScriptException
  {
    Type type = script.lookupDeclaration(name);
    if (!(type instanceof Function)) {
      throw NoSuchFunction(name);
    }
    Function function = (Function)type;
    try {
      return function.execute(this, parameters);

    } catch (ExitException exitex) {
      return exitex.getExitValue();

    } catch (ScriptException scriptex) {
      scriptex.fillInStackTrace();
      throw scriptex;

    } catch (Throwable thrown) {
      if (size()>1) {
        StackFrame frame = peek();
        log().error("Abnormal script termination at '" + frame.getPathinfo() +
          "' line " + frame.getLine() + " in function '" + frame.getFunction().getName() + "'" , thrown);
      } else {
        log().error("Abnormal script termination", thrown);
      }
    }
    return Any.UNDEFINED;
  }

  /* localization */


  public final String getLanguage()
  {
    return _language;
  }


  public final void setLanguage(String language)
  {
    _language = language;
    _locale = new Locale(language, _locale.getCountry());
  }


  public final Locale getLocale()
  {
    return _locale;
  }

 
  public final void setLocale(Locale locale)
  {
    _locale = locale;
  }
 

  public final TimeZone getTimeZone()
  {
    return _timezone;
  }
 

  public final void setTimeZone(TimeZone timezone)
  {
    _timezone = timezone;
  }
 
  /* output */


  public final void setOutputStream(OutputStream output)
  {
    pushOutputStream(output);
  }

 
  public final OutputStream getOutputStream()
  {
    return _output;
  }
 

  public final void pushOutputStream(OutputStream output)
  {
    _output = output;
    _outputStack.push(output);
  }


  public final OutputStream popOutputStream()
  {
    if (!_outputStack.isEmpty()) {
      OutputStream popped = (OutputStream)_outputStack.pop();
      if (!_outputStack.isEmpty()) {
        _output = (OutputStream)_outputStack.peek();
      } else {
        _output = null;
      }
      return popped;
    } else {
      return null;
    }
  }
 
  public final OutputStream peekOutputStream()
  {
    int n = _outputStack.size();
    if (_outputStack.size() > 1) {
      return (OutputStream)_outputStack.elementAt(n - 2);
    } else {
      return null;
    }
  }


  public final void println()
  {
    if (_output != null) {
      try {
        _output.write(NEWLINE, 0, 1);
      } catch (IOException exception) {
        _output = null;
        throw exception(exception);
      }
    } else {
    }
  }


  public final void println(String cdata)
  {
    print(cdata);
    println();
  }


  public final void print(String cdata)
  {
    if ((cdata != null) && (cdata.length() > 0)) {
      if (_output != null) {
        try {
          byte[] array = anvil.util.Conversions.getBytes(cdata);
          _output.write(array, 0, array.length);
        } catch (IOException exception) {
          _output = null;
          throw exception(exception);
        }
      } else {
        log().debug(cdata);
      }
    }
  }

  public final void println(byte[] array)
  {
    if (array == null) {
      return;
    }
    print(array);
    println();
  }

  public final void print(byte[] array)
  {
    if (array == null) {
      return;
    }
    int n = array.length;
    if (n > 0) {
      if (_output != null) {
        try {
          _output.write(array, 0, n);
        } catch (IOException exception) {
          _output = null;
          throw exception(exception);
        }
      } else {
        log().debug(new String(array));
      }
    }
  }
 
  public final void println(byte[] array, int offset, int length)
  {
    if (array == null) {
      return;
    }
    print(array, offset, length);
    println();
  }
 
  public final void print(byte[] array, int offset, int length)
  {
    if (array == null) {
      return;
    }
    if (length > 0) {
      if (_output != null) {
        try {
          _output.write(array, offset, length);
        } catch (IOException exception) {
          _output = null;
          throw exception(exception);
        }
      } else {
        log().debug(new String(array, offset, length));
      }
    }
  }
 

  public final void println(Any value)
  {
    print(value.toBinary());
    println();
  }


  public final void print(Any value)
  {
    print(value.toBinary());
  }



  /** new shortcuts */
 
  public static final Any predec(Any target, String field, Context context)
  {
    return target.setAttribute(context, field, target.getAttribute(context, field).decrease());
  }
 

  public static final Any preinc(Any target, String field, Context context)
  {
    return target.setAttribute(context, field, target.getAttribute(context, field).increase());
  }


  public static final Any postdec(Any target, String field, Context context)
  {
    Any value = target.getAttribute(context, field);
    target.setAttribute(context, field, value.decrease());
    return value;
  }
 

  public static final Any postinc(Any target, String field, Context context)
  {
    Any value = target.getAttribute(context, field);
    target.setAttribute(context, field, value.increase());
    return value;
  }


  public static final Any assign(Any value, Any target, String field, Context context)
  {
    return target.setAttribute(context, field, value);
  }


  public static final Any add(Any value, Any target, String field, Context context)
  {
    return target.setAttribute(context, field, Op.add(target.getAttribute(context, field), value));
  }


  public static final Any sub(Any value, Any target, String field, Context context)
  {
    return target.setAttribute(context, field, Op.sub(target.getAttribute(context, field), value));
  }


  public static final Any mul(Any value, Any target, String field, Context context)
  {
    return target.setAttribute(context, field, Op.mul(target.getAttribute(context, field), value));
  }


  public static final Any div(Any value, Any target, String field, Context context)
  {
    return target.setAttribute(context, field, Op.div(target.getAttribute(context, field), value));
  }


  public static final Any mod(Any value, Any target, String field, Context context)
  {
    return target.setAttribute(context, field, Op.mod(target.getAttribute(context, field), value));
  }


  public static final Any concat(Any value, Any target, String field, Context context)
  {
    return target.setAttribute(context, field, target.getAttribute(context, field).concat(value));
  }
 
 
  public static final Any init(Any value, Any target, String field, Context context)
  {
    Any old = target.getAttribute(context, field);
    if (old.isUndefined()) {
      return target.setAttribute(context, field, value);
    } else {
      return old;
    }
  }


  /* reference shortcuts */

  public static final Any predec(Any target, Any index, Context context)
  {
    return target.setReference(context, index, target.getReference(context, index).decrease());
  }
 

  public static final Any preinc(Any target, Any index, Context context)
  {
    return target.setReference(context, index, target.getReference(context, index).increase());
  }


  public static final Any postdec(Any target, Any index, Context context)
  {
    Any value = target.getReference(context, index);
    target.setReference(context, index, value.decrease());
    return value;
  }
 

  public static final Any postinc(Any target, Any index, Context context)
  {
    Any value = target.getReference(context, index);
    target.setReference(context, index, value.increase());
    return value;
  }


  public static final Any assign(Any value, Any target, Any index, Context context)
  {
    return target.setReference(context, index, value);
  }


  public static final Any add(Any value, Any target, Any index, Context context)
  {
    return target.setReference(context, index, Op.add(target.getReference(context, index), value));
  }


  public static final Any sub(Any value, Any target, Any index, Context context)
  {
    return target.setReference(context, index, Op.sub(target.getReference(context, index), value));
  }


  public static final Any mul(Any value, Any target, Any index, Context context)
  {
    return target.setReference(context, index, Op.mul(target.getReference(context, index), value));
  }


  public static final Any div(Any value, Any target, Any index, Context context)
  {
    return target.setReference(context, index, Op.div(target.getReference(context, index), value));
  }


  public static final Any mod(Any value, Any target, Any index, Context context)
  {
    return target.setReference(context, index, Op.mod(target.getReference(context, index), value));
  }


  public static final Any concat(Any value, Any target, Any index, Context context)
  {
    return target.setReference(context, index, target.getReference(context, index).concat(value));
  }


  public static final Any init(Any value, Any target, Any index, Context context)
  {
    Any old = target.getReference(context, index);
    if (old.isUndefined()) {
      return target.setReference(context, index, value);
    } else {
      return old;
    }
  }


  /* regular expressions */

  public static final boolean match(Context context, Any image, Any pattern)
  {
    Pattern p;
    if (pattern.isPattern()) {
      p = pattern.toPattern();
    } else {
      try {
        p = ObjectPool.createPattern(pattern.toString(), null);
      } catch (MalformedPatternException e) {
        if (context == null) {
          context = Context.getInstance();
        }
        throw context.exception(e);
      }
    }
    Perl5Matcher matcher = new Perl5Matcher();
    return matcher.contains(image.toString(), p);
  }

  public static final boolean nomatch(Context context, Any image, Any pattern)
  {
    return !match(context, image, pattern);
  }


  /* importing */

  public final Any dynamicImport(String source)
  {
    return new anvil.core.runtime.AnyScope(import_(source));
  }


  public final Scope import_(String source)
  {
    Zone zone = zone();
   
    if (source.equals(Modules.NAME)) {
      return zone.getModules();
    }

    Address importing = null;
   
    try {     
      importing = address().resolve(source);
    } catch (anvil.server.ZoneInactiveException e) {
      throw ImportError(e.getMessage(), null);
    }
   
    checkImport(frame().getPathinfo(), importing.getPathinfo());
   
    try {
      return zone.getServer().getCache().load(importing).getModule();
     
    } catch (ForgingException e) {
      throw ImportError(source, e.getErrorListener());
     
    } catch (IOException e) {
      throw exception(e);
     
    } catch (Throwable t) {
      log().error("Import failed", t);
      throw exception(t);
    }
  } 

  /*reflection*/ 
 
  public Reflection reflect(String classname)
  {
    checkReflection(classname);
    Reflection reflection = ObjectPool.getReflection(classname);
    if (reflection == null) {
      reflection = zone().findJava(classname);
    }
    if (reflection == null) {
      throw ClassNotFound(classname);
    }
    return reflection;
  }

  private Reflection reflect0(String classname)
  {
    Reflection reflection = ObjectPool.getReflection(classname);
    if (reflection == null) {
      reflection = zone().findJava(classname);
    }
    if (reflection == null) {
      throw ClassNotFound(classname);
    }
    return reflection;
  }
   
 
  /* piping */
 
  public final Any pipe(Any list, Any pipe)
  {
    return new anvil.core.AnyBindingEnumeration(
      new anvil.core.AnyUtils.PipeEnumeration(
        this, pipe, list.enumeration(), Any.UNDEFINED));
  }
 
  /* foreach */
 
  public final Any foreach(Any list, Any block)
  {
    Any rv = Any.UNDEFINED;
    BindingEnumeration e = list.enumeration();
    Any[] args = new Any[2];
    while(e.hasMoreElements()) {
      args[1] = Any.create(e.nextKey());
      args[0] = Any.create(e.nextElement());
      rv = block.execute(this, args);
    }
    return rv;
  }


  /* multiassign */

  public final Any nth(Any value, int index)
  {
    if (value.isEnumeration()) {
      Enumeration e = value.enumeration();
      if (e.hasMoreElements()) {
        return Any.create(e.nextElement());
      }
    } else if (value.isArray()) {
      value = value.toArray().elementAt(index);
      if (value != null) {
        return value;
      }
    } else {
      return value.checkReference(this, Any.create(index));
    }
    return Any.UNDEFINED;
 


  /* exceptions */
 
  public ScriptException TypeError(String message)
  {
    return new ScriptException(new Throwables.TypeError(this, message));
  }

  public ScriptException BadParameter(String message)
  {
    return new ScriptException(new Throwables.TypeError.BadParameter(this, message));
  }

  public ScriptException NotEnoughParameters()
  {
    return new ScriptException(new Throwables.TypeError.NotEnoughParameters(this, null));
  }   

  public ScriptException NotEnoughParameters(String message)
  {
    return new ScriptException(new Throwables.TypeError.NotEnoughParameters(this, message));
  }   
 
  public ScriptException NotEnoughParameters(int index)
  {
    return new ScriptException(new Throwables.TypeError.NotEnoughParameters(this, Register.getNameOf(index)));
  }     

  public ScriptException NoSuchMethod(String message)
  {
    return new ScriptException(new Throwables.TypeError.NoSuchMethod(this, message));
 

  public ScriptException NoSuchMethod(int index)
  {
    return new ScriptException(new Throwables.TypeError.NoSuchMethod(this, Register.getNameOf(index)));
  }

  public ScriptException NoSuchMethod(String classname, int index)
  {
    return new ScriptException(new Throwables.TypeError.NoSuchMethod(this, classname + '.' + Register.getNameOf(index)));
  }
 
  public ScriptException NoSuchMember(String message)
  {
    return new ScriptException(new Throwables.TypeError.NoSuchMember(this, message));
 

  public ScriptException NoSuchFunction(String message)
  {
    return new ScriptException(new Throwables.TypeError.NoSuchFunction(this, message));
 

  public ScriptException NoSuchClass(String message)
  {
    return new ScriptException(new Throwables.TypeError.NoSuchClass(this, message));
 

  public ScriptException NoSuchEntity(String message)
  {
    return new ScriptException(new Throwables.TypeError.NoSuchEntity(this, message));
  }

  public ScriptException NoInstance(String message)
  {
    return new ScriptException(new Throwables.TypeError.NoInstance(this, message));
 
 
  public ScriptException InstantiationError(String message)
  {
    return new ScriptException(new Throwables.TypeError.InstantiationError(this, message));
 
 
  public ScriptException AttributeError(String message)
  {
    return new ScriptException(new Throwables.TypeError.AttributeError(this, message));
  }

  public ScriptException ReferenceError(String message)
  {
    return new ScriptException(new Throwables.TypeError.ReferenceError(this, message));
  }

  public ScriptException CallError(String message)
  {
    return new ScriptException(new Throwables.TypeError.CallError(this, message));
  }
   

  public ScriptException BadState(String message)
  {
    return new ScriptException(new Throwables.BadState(this, message));
  }

  public ScriptException AssertFailed(String message)
  {
    return new ScriptException(new Throwables.AssertFailed(this, message));
  }




  public ScriptException CorruptedSerialization()
  {
    return new ScriptException(new Throwables.CorruptedSerialization(this, null));
  }

  public ScriptException CorruptedSerialization(String message)
  {
    return new ScriptException(new Throwables.CorruptedSerialization(this, message));
  }

  public ScriptException MalformedPattern(String message)
  {
    return new ScriptException(new Throwables.MalformedPattern(this, message));
  }

  public ScriptException AcquireError(String message)
  {
    return new ScriptException(new Throwables.AcquireError(this, message));
  }
 
   public ScriptException AccessDenied(String message)
  {
    return new ScriptException(new Throwables.AccessDenied(this, message));
 

 
  public ScriptException ClassNotFound(String message)
  {
    return new ScriptException(new Throwables.ClassNotFound(this, message));
 

  public ScriptException XMLError(String message, ErrorListener listener)
  {
    return new ScriptException(new Throwables.XMLError(this, message, listener));
  }

 
  public ScriptException InternalError(String message)
  {
    return new ScriptException(new Throwables.InternalError(this, message));
 

  public ScriptException ImportError(String message, ErrorListener listener)
  {
    return new ScriptException(new Throwables.ImportError(this, message, listener));
 
 
 
  public ScriptException Interrupted(String message)
  {
    return new ScriptException(new Throwables.Interrupted(this, message));
  }   
 

  public ScriptException SQLError(java.sql.SQLException exception)
  {
    return new ScriptException(new Throwables.SQLError(this, exception));
  }   


  public ScriptException OperationFailed(String message)
  {
    return new ScriptException(new Throwables.OperationFailed(this, message));
  }   
 

  public final ScriptException exception(Throwable throwable)
  {
    if (throwable instanceof java.io.IOException) {
      return exception((java.io.IOException)throwable);
    }
    if (throwable instanceof java.sql.SQLException) {
      return exception((java.sql.SQLException)throwable);
    }
    if (throwable instanceof javax.naming.NamingException) {
      return exception((javax.naming.NamingException)throwable);
    }
    if (throwable instanceof anvil.server.OperationFailedException) {
      return exception((anvil.server.OperationFailedException)throwable);
    }
    return new ScriptException(new Throwables.JavaError(this, throwable));
  }


  public final ScriptException exception(java.io.IOException e)
  {
    Any t;
    if (e instanceof java.io.FileNotFoundException) {
      t = new anvil.core.Throwables.IOError.FileNotFound(this, e.getMessage());
    }
    else if (e instanceof java.io.EOFException) {
      t = new anvil.core.Throwables.IOError.EndOfFile(this, e.getMessage());
    }
    else if (e instanceof java.io.InterruptedIOException) {
      t = new anvil.core.Throwables.IOError.InterruptedIO(this, e.getMessage());
    }
    else if (e instanceof java.io.SyncFailedException) {
      t = new anvil.core.Throwables.IOError.SyncFailed(this, e.getMessage());
    }
    else if (e instanceof java.net.SocketException) {
      return exception((java.net.SocketException)e);
    }
    else if (e instanceof java.net.MalformedURLException) {
      t = new anvil.core.Throwables.IOError.MalformedURL(this, e.getMessage());
    }
    else if (e instanceof java.net.UnknownHostException) {
      t = new anvil.core.Throwables.IOError.UnknownHost(this, e.getMessage());
    }
    else if (e instanceof java.net.ProtocolException) {
      t = new anvil.core.Throwables.IOError.ProtocolError(this, e.getMessage());
    }
    else if (e instanceof java.net.UnknownServiceException) {
      t = new anvil.core.Throwables.IOError.UnknownService(this, e.getMessage());
    }
    else {
      t = new anvil.core.Throwables.IOError(this, e.getMessage());
    }
    return new ScriptException(t);
  }


  public final ScriptException exception(java.net.SocketException e)
  {
    Any t;
    if (e instanceof java.net.BindException) {
      t = new anvil.core.Throwables.IOError.SocketError.BindError(this, e.getMessage());
    }
    else if (e instanceof java.net.ConnectException) {
      t = new anvil.core.Throwables.IOError.SocketError.ConnectError(this, e.getMessage());
    }
    else if (e instanceof java.net.NoRouteToHostException) {
      t = new anvil.core.Throwables.IOError.SocketError.NoRouteToHost(this, e.getMessage());
    }
    else {
      t = new anvil.core.Throwables.IOError.SocketError(this, e.getMessage());
    }
    return new ScriptException(t);
  }


  public final ScriptException exception(java.sql.SQLException e)
  {
    return new ScriptException(new anvil.core.Throwables.SQLError(this, e));
  }


  public final ScriptException exception(javax.naming.NamingException e)
  {
    return new ScriptException(Any.create(e));
  }


  public final ScriptException exception(anvil.server.OperationFailedException e)
  {
    return new ScriptException(new anvil.core.Throwables.OperationFailed(this, e.getMessage()));
 
}

TOP

Related Classes of anvil.script.Context

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.