Example #1
0
 public int compare(MappingWithDirection o1, MappingWithDirection o2) {
   Class<?> class1 =
       o1.mapping.sideA.isAssignableFrom(target) ? o1.mapping.sideA : o1.mapping.sideB;
   Class<?> class2 =
       o2.mapping.sideA.isAssignableFrom(target) ? o2.mapping.sideA : o2.mapping.sideB;
   return class1 == class2 ? 0 : class1.isAssignableFrom(class2) ? -1 : 1;
 }
Example #2
0
  /**
   * Given a map between a string and an object of unknown type, attempt to retrieve what value is
   * mapped to from the specified string and validate that the actual type matches the specified
   * class.
   *
   * @return Null if the types do not match, or the value
   */
  private static Object validateAndGet(Map<String, Object> m, String s, Class<?> c)
      throws MissingMappingException, UnexpectedTypeException {
    Object o = m.get(s);
    if (o == null) throw new MissingMappingException(s);

    if (!c.isAssignableFrom(o.getClass()))
      throw new UnexpectedTypeException(s, c.toString(), o.getClass().toString());
    else return o;
  }
 private static void tryCatch(String fs, Class<?> ex) {
   boolean caught = false;
   try {
     test(fs);
   } catch (Throwable x) {
     if (ex.isAssignableFrom(x.getClass())) caught = true;
   }
   if (!caught) fail(fs, ex);
   else pass();
 }
    /**
     * Construct an RPC server.
     *
     * @param protocolClass - the protocol being registered can be null for compatibility with old
     *     usage (see below for details)
     * @param protocolImpl the protocol impl that will be called
     * @param conf the configuration to use
     * @param bindAddress the address to bind on to listen for connection
     * @param port the port to listen for connections on
     * @param numHandlers the number of method handler threads to run
     * @param verbose whether each call should be logged
     */
    public Server(
        Class<?> protocolClass,
        Object protocolImpl,
        Configuration conf,
        String bindAddress,
        int port,
        int numHandlers,
        int numReaders,
        int queueSizePerHandler,
        boolean verbose,
        SecretManager<? extends TokenIdentifier> secretManager,
        String portRangeConfig)
        throws IOException {
      super(
          bindAddress,
          port,
          null,
          numHandlers,
          numReaders,
          queueSizePerHandler,
          conf,
          classNameBase(protocolImpl.getClass().getName()),
          secretManager,
          portRangeConfig);

      this.verbose = verbose;

      Class<?>[] protocols;
      if (protocolClass == null) { // derive protocol from impl
        /*
         * In order to remain compatible with the old usage where a single
         * target protocolImpl is suppled for all protocol interfaces, and
         * the protocolImpl is derived from the protocolClass(es)
         * we register all interfaces extended by the protocolImpl
         */
        protocols = RPC.getProtocolInterfaces(protocolImpl.getClass());

      } else {
        if (!protocolClass.isAssignableFrom(protocolImpl.getClass())) {
          throw new IOException(
              "protocolClass "
                  + protocolClass
                  + " is not implemented by protocolImpl which is of class "
                  + protocolImpl.getClass());
        }
        // register protocol class and its super interfaces
        registerProtocolAndImpl(RPC.RpcKind.RPC_WRITABLE, protocolClass, protocolImpl);
        protocols = RPC.getProtocolInterfaces(protocolClass);
      }
      for (Class<?> p : protocols) {
        if (!p.equals(VersionedProtocol.class)) {
          registerProtocolAndImpl(RPC.RpcKind.RPC_WRITABLE, p, protocolImpl);
        }
      }
    }
  @SuppressWarnings("unchecked")
  public static <T> T convert(Context context, Class<T> type) {
    if (type.isAssignableFrom(Context.class)) {
      return (T) context;
    }
    if (type.isAssignableFrom(Map.class)) {
      return (T) context.keyValues();
    }
    if (isUrlEncodedForm(context)) {
      return convertValue(context.keyValues(), type);
    }

    String json;
    try {
      json = context.request().getContent();
    } catch (IOException e) {
      throw new IllegalArgumentException("Unable read request content", e);
    }

    return fromJson(json, type);
  }
Example #6
0
 @Nonnull
 private Iterator<Class<? extends T>> load(@Nonnull URL url) {
   try {
     try (final InputStream is = url.openStream()) {
       try (final Reader reader = new InputStreamReader(is)) {
         try (final BufferedReader br = new BufferedReader(reader)) {
           final Collection<Class<? extends T>> types = new ArrayList<>();
           String line = br.readLine();
           while (line != null) {
             final String trimmedLine = line.trim();
             if (!trimmedLine.isEmpty()) {
               final Class<?> plainClass;
               try {
                 plainClass = _classLoader.loadClass(trimmedLine);
               } catch (ClassNotFoundException e) {
                 throw new IllegalStateException(
                     "Could not find a class named " + trimmedLine + " defined in " + url + ".",
                     e);
               }
               if (_expectedType != null && !_expectedType.isAssignableFrom(plainClass)) {
                 throw new IllegalStateException(
                     "Class named "
                         + trimmedLine
                         + " defined in "
                         + url
                         + " is not of expected type "
                         + _expectedType.getName()
                         + ".");
               }
               // noinspection unchecked
               types.add((Class<? extends T>) plainClass);
             }
             line = br.readLine();
           }
           return types.iterator();
         }
       }
     }
   } catch (IOException e) {
     throw new RuntimeException(
         "Could not load classes of type " + _baseType.getName() + " from " + url + ".", e);
   }
 }
  /**
   * @return all of the classes x in the given directory (recursively) such that
   *     clazz.isAssignableFrom(x).
   */
  private List<Class> getAssignableClasses(File path, Class<TetradSerializable> clazz) {
    if (!path.isDirectory()) {
      throw new IllegalArgumentException("Not a directory: " + path);
    }

    @SuppressWarnings("Convert2Diamond")
    List<Class> classes = new LinkedList<>();
    File[] files = path.listFiles();

    if (files == null) {
      throw new NullPointerException();
    }

    for (File file : files) {
      if (file.isDirectory()) {
        classes.addAll(getAssignableClasses(file, clazz));
      } else {
        String packagePath = file.getPath();
        packagePath = packagePath.replace('\\', '.');
        packagePath = packagePath.replace('/', '.');
        packagePath = packagePath.substring(packagePath.indexOf("edu.cmu"), packagePath.length());
        int index = packagePath.indexOf(".class");

        if (index == -1) {
          continue;
        }

        packagePath = packagePath.substring(0, index);

        try {
          Class _clazz = getClass().getClassLoader().loadClass(packagePath);

          if (clazz.isAssignableFrom(_clazz) && !_clazz.isInterface()) {
            classes.add(_clazz);
          }
        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        }
      }
    }

    return classes;
  }
Example #8
0
  /**
   * @param classloader
   * @param superClass
   * @param classes
   * @param className
   */
  @SuppressWarnings("unchecked")
  private static void checkAndAddClass(
      ClassLoader classloader, Class superClass, LinkedList<Class> classes, String className) {
    if (className.indexOf('$') > -1) return;

    try {
      Class subClass = classloader.loadClass(className);

      if (subClass != null
          && !superClass.equals(subClass)
          && superClass.isAssignableFrom(subClass)
          && !subClass.isInterface()
          && !classes.contains(subClass)) {
        classes.add(subClass);
      }
    } catch (Throwable th) {
      logger.log(Level.WARNING, "checkAndAddClass error", th);
    }
  }
 private static boolean isInstanceOf(Object object, final String className)
     throws ClassNotFoundException {
   final Class<?> ethalon = object.getClass().getClassLoader().loadClass(className);
   return ethalon.isAssignableFrom(object.getClass());
 }
  /**
   * Checks all of the classes in the serialization scope that implement TetradSerializable to make
   * sure all of their fields are either themselves (a) primitive, (b) TetradSerializable, or (c)
   * assignable from types designated as safely serializable by virtue of being included in the
   * safelySerializableTypes array (see), or are arrays whose lowest order component types satisfy
   * either (a), (b), or (c). Safely serializable classes in the Java API currently include
   * collections classes, plus String and Class. Collections classes are included, since their types
   * will be syntactically checkable in JDK 1.5. String and Class are members of a broader type of
   * Class whose safely can by checked by making sure there is no way to pass into them via
   * constructor or method argument any object that is not TetradSerializable or safely
   * serializable. But it's easy enough now to just make a list.
   *
   * @see #safelySerializableTypes
   */
  public void checkNestingOfFields() {
    List classes = getAssignableClasses(new File(getSerializableScope()), TetradSerializable.class);

    boolean foundUnsafeField = false;

    for (Object aClass : classes) {
      Class clazz = (Class) aClass;

      if (TetradSerializableExcluded.class.isAssignableFrom(clazz)) {
        continue;
      }

      Field[] fields = clazz.getDeclaredFields();

      FIELDS:
      for (Field field : fields) {
        //                System.out.println(field);

        if (Modifier.isTransient(field.getModifiers())) {
          continue;
        }

        if (Modifier.isStatic(field.getModifiers())) {
          continue;
        }

        Class type = field.getType();

        while (type.isArray()) {
          type = type.getComponentType();
        }

        if (type.isPrimitive()) {
          continue;
        }

        if (type.isEnum()) {
          continue;
        }

        //                // Printing out Collections fields temporarily.
        //                if (Collection.class.isAssignableFrom(type)) {
        //                    System.out.println("COLLECTION FIELD: " + field);
        //                }
        //
        //                if (Map.class.isAssignableFrom(type)) {
        //                    System.out.println("MAP FIELD: " + field);
        //                }

        if (TetradSerializable.class.isAssignableFrom(type)
            && !TetradSerializableExcluded.class.isAssignableFrom(clazz)) {
          continue;
        }

        for (Class safelySerializableClass : safelySerializableTypes) {
          if (safelySerializableClass.isAssignableFrom(type)) {
            continue FIELDS;
          }
        }

        // A reference in an inner class to the outer class.
        if (field.getName().equals("this$0")) {
          continue;
        }

        System.out.println("UNSAFE FIELD:" + field);
        foundUnsafeField = true;
      }
    }

    if (foundUnsafeField) {
      throw new RuntimeException("Unsafe serializable fields found. Please " + "fix immediately.");
    }
  }
Example #11
0
  public static Data getHTTPData(
      HttpServletRequest req, HttpServletResponse res, String surl, long since)
      throws DataSourceException, IOException {

    int tries = 1;

    // timeout msecs of time we're allowed in this routine
    // we must return or throw an exception.  0 means infinite.
    int timeout = mTimeout;
    if (req != null) {
      String timeoutParm = req.getParameter("timeout");
      if (timeoutParm != null) {
        timeout = Integer.parseInt(timeoutParm);
      }
    }

    long t1 = System.currentTimeMillis();
    long elapsed = 0;
    if (surl == null) {
      surl = getURL(req);
    }

    while (true) {
      String m = null;

      long tout;
      if (timeout > 0) {
        tout = timeout - elapsed;
        if (tout <= 0) {
          throw new InterruptedIOException(
              /* (non-Javadoc)
               * @i18n.test
               * @org-mes=p[0] + " timed out"
               */
              org.openlaszlo.i18n.LaszloMessages.getMessage(
                  HTTPDataSource.class.getName(), "051018-194", new Object[] {surl}));
        }
      } else {
        tout = 0;
      }

      try {
        HttpData data = getDataOnce(req, res, since, surl, 0, (int) tout);
        if (data.code >= 400) {
          data.release();
          throw new DataSourceException(errorMessage(data.code));
        }
        return data;
      } catch (HttpRecoverableException e) {
        // This type of exception should be retried.
        if (tries++ > mMaxRetries) {
          throw new InterruptedIOException(
              /* (non-Javadoc)
               * @i18n.test
               * @org-mes="too many retries, exception: " + p[0]
               */
              org.openlaszlo.i18n.LaszloMessages.getMessage(
                  HTTPDataSource.class.getName(), "051018-217", new Object[] {e.getMessage()}));
        }
        mLogger.warn(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="retrying a recoverable exception: " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-226", new Object[] {e.getMessage()}));
      } catch (HttpException e) {
        String msg =
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="HttpException: " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-235", new Object[] {e.getMessage()});
        throw new IOException(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="HttpException: " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-235", new Object[] {e.getMessage()}));
      } catch (IOException e) {

        try {
          Class ssle = Class.forName("javax.net.ssl.SSLException");
          if (ssle.isAssignableFrom(e.getClass())) {
            throw new DataSourceException(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="SSL exception: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(
                    HTTPDataSource.class.getName(), "051018-256", new Object[] {e.getMessage()}));
          }
        } catch (ClassNotFoundException cfne) {
        }

        throw e;
      }

      long t2 = System.currentTimeMillis();
      elapsed = (t2 - t1);
    }
  }
  private Object getParam(
      final Class<?> pClass,
      final String pName,
      final ParamType pType,
      final String pXpath,
      final HttpMessage pMessage)
      throws XmlException {
    Object result = null;
    switch (pType) {
      case GET:
        result = getParamGet(pName, pMessage);
        break;
      case POST:
        result = getParamPost(pName, pMessage);
        break;
      case QUERY:
        result = getParamGet(pName, pMessage);
        if (result == null) {
          result = getParamPost(pName, pMessage);
        }
        break;
      case VAR:
        result = mPathParams.get(pName);
        break;
      case XPATH:
        result = getParamXPath(pClass, pXpath, pMessage.getBody());
        break;
      case BODY:
        result = getBody(pClass, pMessage);
        break;
      case ATTACHMENT:
        result = getAttachment(pClass, pName, pMessage);
        break;
      case PRINCIPAL:
        {
          final Principal principal = pMessage.getUserPrincipal();
          if (pClass.isAssignableFrom(String.class)) {
            result = principal.getName();
          } else {
            result = principal;
          }
          break;
        }
    }
    // XXX generizice this and share the same approach to unmarshalling in ALL code
    // TODO support collection/list parameters
    if ((result != null) && (!pClass.isInstance(result))) {
      if ((Types.isPrimitive(pClass) || (Types.isPrimitiveWrapper(pClass)))
          && (result instanceof String)) {
        try {
          result = Types.parsePrimitive(pClass, ((String) result));
        } catch (NumberFormatException e) {
          throw new HttpResponseException(
              HttpServletResponse.SC_BAD_REQUEST, "The argument given is invalid", e);
        }
      } else if (Enum.class.isAssignableFrom(pClass)) {
        @SuppressWarnings({"rawtypes"})
        final Class clazz = pClass;
        @SuppressWarnings("unchecked")
        final Enum<?> tmpResult = Enum.valueOf(clazz, result.toString());
        result = tmpResult;
      } else if (result instanceof Node) {
        XmlDeserializer factory = pClass.getAnnotation(XmlDeserializer.class);
        if (factory != null) {
          try {
            result =
                factory
                    .value()
                    .newInstance()
                    .deserialize(XmlStreaming.newReader(new DOMSource((Node) result)));
          } catch (IllegalAccessException | InstantiationException e) {
            throw new XmlException(e);
          }
        } else {
          result = JAXB.unmarshal(new DOMSource((Node) result), pClass);
        }
      } else {
        final String s = result.toString();
        // Only wrap when we don't start with <
        final char[] requestBody =
            (s.startsWith("<") ? s : "<wrapper>" + s + "</wrapper>").toCharArray();
        if (requestBody.length > 0) {
          result = JAXB.unmarshal(new CharArrayReader(requestBody), pClass);
        } else {
          result = null;
        }
      }
    }

    return result;
  }
Example #13
0
 /** Does the <code>DataFlavor</code> represent a <code>java.io.InputStream</code>? */
 public boolean isRepresentationClassInputStream() {
   return ioInputStreamClass.isAssignableFrom(representationClass);
 }
  /* methods that take an EventListener Class Type to create an EventAdapterClass */
  public static Class makeEventAdapterClass(Class listenerType, boolean writeClassFile) {
    DebugLog.stdoutPrintln("EventAdapterGenerator", DebugLog.BSF_LOG_L3);

    if (EVENTLISTENER.isAssignableFrom(listenerType)) {
      boolean exceptionable = false;
      boolean nonExceptionable = false;
      byte constantPool[] = null;
      short cpBaseIndex;
      short cpCount = 0;
      short cpExceptionBaseIndex;
      short exceptionableCount;
      short nonExceptionableCount;

      /* Derive Names */
      String listenerTypeName = listenerType.getName();
      DebugLog.stdoutPrintln("  ListenerTypeName: " + listenerTypeName, DebugLog.BSF_LOG_L3);
      String adapterClassName =
          CLASSPACKAGE
              + (listenerTypeName.endsWith("Listener")
                      ? listenerTypeName.substring(0, listenerTypeName.length() - 8)
                      : listenerTypeName)
                  .replace('.', '_')
              + "Adapter";
      String finalAdapterClassName = adapterClassName;
      Class cached = null;
      int suffixIndex = 0;

      do {
        if (null != (cached = ldr.getLoadedClass(finalAdapterClassName))) {
          DebugLog.stdoutPrintln("cached:  " + cached, DebugLog.BSF_LOG_L3);
          try {
            if (!listenerType.isAssignableFrom(cached))
              finalAdapterClassName = adapterClassName + "_" + suffixIndex++;
            else return cached;
          } catch (VerifyError ex) {
            System.err.println(ex.getMessage());
            ex.printStackTrace();
            return cached;
          }
        }
      } while (cached != null);

      String eventListenerName = listenerTypeName.replace('.', '/');

      /* method stuff */
      java.lang.reflect.Method lms[] = listenerType.getMethods();

      /* ****************************************************************************************** */
      // Listener interface
      // Class name
      cpCount += 4;

      // cp item 17
      constantPool = Bytecode.addUtf8(constantPool, eventListenerName);

      // cp item 18
      constantPool = Bytecode.addUtf8(constantPool, finalAdapterClassName);

      // cp item 19
      constantPool = Bytecode.addClass(constantPool, (short) 17);

      // cp item 20
      constantPool = Bytecode.addClass(constantPool, (short) 18);

      // do we have nonExceptionalble event, exceptionable or both
      for (int i = 0; i < lms.length; ++i) {
        Class exceptionTypes[] = lms[i].getExceptionTypes();
        if (0 < exceptionTypes.length) {
          exceptionable = true;
        } else {
          nonExceptionable = true;
        }
      } /* End for*/

      /* ****************************************************************************************** */
      // optional inclusion of nonexceptional events affects exceptional events indices

      nonExceptionableCount = 0;
      if (nonExceptionable) {
        nonExceptionableCount = 3;
        cpCount += nonExceptionableCount;

        // cp item 21
        constantPool = Bytecode.addUtf8(constantPool, "processEvent");

        // cp item 22
        constantPool = Bytecode.addNameAndType(constantPool, (short) 21, (short) 8);

        // cp item 23
        constantPool = Bytecode.addInterfaceMethodRef(constantPool, (short) 12, (short) 22);
      }

      /* ****************************************************************************************** */
      // optional inclusion of exceptional events affects CP Items which follow for specific methods

      exceptionableCount = 0;
      if (exceptionable) {
        int classIndex = BASECPCOUNT + cpCount + 1;
        int nameIndex = BASECPCOUNT + cpCount + 0;
        int natIndex = BASECPCOUNT + cpCount + 3;

        exceptionableCount = 5;
        cpCount += exceptionableCount;

        // cp item 24 or 21
        constantPool = Bytecode.addUtf8(constantPool, "processExceptionableEvent");

        // cp item 25 or 22
        constantPool = Bytecode.addUtf8(constantPool, "java/lang/Exception");

        // cp item 26 or 23
        constantPool = Bytecode.addClass(constantPool, (short) classIndex);

        // cp item 27 or 24
        constantPool = Bytecode.addNameAndType(constantPool, (short) nameIndex, (short) 8);

        // cp item 28 or 25
        constantPool = Bytecode.addInterfaceMethodRef(constantPool, (short) 12, (short) natIndex);
      }

      // base index for method cp references
      cpBaseIndex = (short) (BASECPCOUNT + cpCount);
      DebugLog.stderrPrintln("cpBaseIndex: " + cpBaseIndex, DebugLog.BSF_LOG_L3);

      for (int i = 0; i < lms.length; ++i) {
        String eventMethodName = lms[i].getName();
        String eventName = lms[i].getParameterTypes()[0].getName().replace('.', '/');
        cpCount += 3;
        // cp items for event methods
        constantPool = Bytecode.addUtf8(constantPool, eventMethodName);
        constantPool = Bytecode.addUtf8(constantPool, ("(L" + eventName + ";)V"));
        constantPool = Bytecode.addString(constantPool, (short) (BASECPCOUNT + cpCount - 3));
      } /* End for*/

      boolean propertyChangeFlag[] = new boolean[lms.length];
      int cpIndexPCE = 0;
      for (int i = 0; i < lms.length; ++i) {
        String eventName = lms[i].getParameterTypes()[0].getName().replace('.', '/');
        // cp items for PropertyChangeEvent special handling
        if (eventName.equalsIgnoreCase("java/beans/PropertyChangeEvent")) {
          propertyChangeFlag[i] = true;
          if (0 == cpIndexPCE) {
            constantPool = Bytecode.addUtf8(constantPool, eventName);
            constantPool = Bytecode.addUtf8(constantPool, "getPropertyName");
            constantPool = Bytecode.addUtf8(constantPool, "()Ljava/lang/String;");
            constantPool = Bytecode.addClass(constantPool, (short) (BASECPCOUNT + cpCount));
            constantPool =
                Bytecode.addNameAndType(
                    constantPool,
                    (short) (BASECPCOUNT + cpCount + 1),
                    (short) (BASECPCOUNT + cpCount + 2));
            constantPool =
                Bytecode.addMethodRef(
                    constantPool,
                    (short) (BASECPCOUNT + cpCount + 3),
                    (short) (BASECPCOUNT + cpCount + 4));
            cpCount += 6;
            cpIndexPCE = BASECPCOUNT + cpCount - 1;
          }
        } else {
          propertyChangeFlag[i] = false;
        }
      } /* End for*/

      cpExceptionBaseIndex = (short) (BASECPCOUNT + cpCount);
      DebugLog.stderrPrintln("cpExceptionBaseIndex: " + cpExceptionBaseIndex, DebugLog.BSF_LOG_L3);

      int excpIndex[][] = new int[lms.length][];
      for (int i = 0; i < lms.length; ++i) {
        Class exceptionTypes[] = lms[i].getExceptionTypes();
        excpIndex[i] = new int[exceptionTypes.length];
        for (int j = 0; j < exceptionTypes.length; j++) {
          constantPool =
              Bytecode.addUtf8(constantPool, exceptionTypes[j].getName().replace('.', '/'));
          constantPool = Bytecode.addClass(constantPool, (short) (BASECPCOUNT + cpCount));
          excpIndex[i][j] = BASECPCOUNT + cpCount + 1;
          cpCount += 2;
        }
      } /* End for*/
      /* end constant pool */

      /* ************************************************************************************************ */
      // put the Class byte array together

      /* start */
      byte newClass[] = CLASSHEADER; // magic, version      (fixed)
      short count = (short) (BASECPCOUNT + cpCount);
      newClass = ByteUtility.addBytes(newClass, count); // constant_pool_count (variable)
      newClass = ByteUtility.addBytes(newClass, BASECP); // constant_pool       (fixed)
      newClass = ByteUtility.addBytes(newClass, constantPool); // constant_pool       (variable)
      newClass = ByteUtility.addBytes(newClass, FIXEDCLASSBYTES); // see FIXEDCLASSBYTES (fixed)
      newClass =
          ByteUtility.addBytes(
              newClass, (short) (lms.length + 1)); // method_count        (variable)
      newClass = ByteUtility.addBytes(newClass, INITMETHOD); // constructor <init>  (fixed)
      // methods

      /* ****************************************************************************************** */
      /* loop over listener methods from listenerType */
      for (int i = 0; i < lms.length; ++i) {
        newClass = ByteUtility.addBytes(newClass, (short) 1); // access_flags             (fixed)
        newClass =
            ByteUtility.addBytes(
                newClass, (short) (cpBaseIndex + 3 * i + 0)); // name_index               (variable)
        newClass =
            ByteUtility.addBytes(
                newClass, (short) (cpBaseIndex + 3 * i + 1)); // descriptor_index         (variable)
        newClass = ByteUtility.addBytes(newClass, (short) 1); // attribute_count          (fixed)
        newClass = ByteUtility.addBytes(newClass, (short) 3); // attribute_name_index code(fixed)

        // Code Attribute Length
        int length = 32;
        if (0 < excpIndex[i].length) {
          length += 5 + 8 * (1 + excpIndex[i].length);
        }
        if (propertyChangeFlag[i]) {
          length += 2;
        }
        newClass =
            ByteUtility.addBytes(newClass, (long) length); // attribute_length         (variable)

        // start code attribute
        newClass = ByteUtility.addBytes(newClass, (short) 6); // max_stack                (fixed)
        newClass = ByteUtility.addBytes(newClass, (short) 3); // max_locals               (fixed)

        // Code Length
        length = 20;
        if (exceptionable && 0 < excpIndex[i].length) {
          length += 5;
        }
        if (propertyChangeFlag[i]) {
          length += 2;
        }
        newClass =
            ByteUtility.addBytes(newClass, (long) length); // code_length              (variable)

        // start code
        newClass = ByteUtility.addBytes(newClass, (byte) 0x2A); // aload_0                  (fixed)
        newClass = ByteUtility.addBytes(newClass, (byte) 0xB4); // getfield                 (fixed)
        newClass = ByteUtility.addBytes(newClass, (short) 15); // index                    (fixed)

        if (propertyChangeFlag[i]) { // the propertyName is passed as the first parameter
          newClass =
              ByteUtility.addBytes(newClass, (byte) 0x2B); // aload_1                  (fixed)
          newClass =
              ByteUtility.addBytes(newClass, (byte) 0xB6); // invokevirtual            (fixed)
          newClass =
              ByteUtility.addBytes(
                  newClass, (short) cpIndexPCE); // methodref                (variable)
        } else { // the eventMethodName is passed as the first parameter
          // Target for method invocation.
          newClass = ByteUtility.addBytes(newClass, (byte) 0x12); // ldc                    (fixed)
          newClass =
              ByteUtility.addBytes(
                  newClass, (byte) (cpBaseIndex + 3 * i + 2)); // index (byte)           (variable)
        }

        newClass = ByteUtility.addBytes(newClass, (byte) 0x04); // iconst_1                 (fixed)
        newClass = ByteUtility.addBytes(newClass, (byte) 0xBD); // anewarray                (fixed)
        newClass = ByteUtility.addBytes(newClass, (short) 10); // Class java/lang/Object   (fixed)
        newClass = ByteUtility.addBytes(newClass, (byte) 0x59); // dup                      (fixed)
        newClass = ByteUtility.addBytes(newClass, (byte) 0x03); // iconst_0                 (fixed)
        newClass = ByteUtility.addBytes(newClass, (byte) 0x2B); // aload_1                  (fixed)
        newClass = ByteUtility.addBytes(newClass, (byte) 0x53); // aastore                  (fixed)
        newClass = ByteUtility.addBytes(newClass, (byte) 0xB9); // invokeinterface          (fixed)

        // index to processEvent or processExceptionableEvent method
        length = 23; // actually an index into cp
        if (exceptionable && nonExceptionable) { // interface method index
          if (0 < lms[i].getExceptionTypes().length) {
            length += 5;
          }
        } else if (exceptionable) {
          length += 2;
        }
        newClass =
            ByteUtility.addBytes(newClass, (short) length); // index (process??????...) (variable)

        newClass = ByteUtility.addBytes(newClass, (byte) 0x03); // iconst_0                 (fixed)
        newClass = ByteUtility.addBytes(newClass, (byte) 0x00); // noop                     (fixed)
        newClass = ByteUtility.addBytes(newClass, (byte) 0xB1); // return                   (fixed)

        if (exceptionable && 0 < excpIndex[i].length) { // exception code
          newClass =
              ByteUtility.addBytes(newClass, (byte) 0x4D); // astore_2                 (fixed)
          newClass =
              ByteUtility.addBytes(newClass, (byte) 0x2C); // aload_2                  (fixed)
          newClass =
              ByteUtility.addBytes(newClass, (byte) 0xBF); // athrow                   (fixed)
          newClass =
              ByteUtility.addBytes(newClass, (byte) 0x57); // pop                      (fixed)
          newClass =
              ByteUtility.addBytes(newClass, (byte) 0xB1); // return                   (fixed)
          // end code

          // exception table
          length = excpIndex[i].length;
          newClass =
              ByteUtility.addBytes(
                  newClass, (short) (1 + length)); // exception_table_length   (variable)
          for (int j = 0; j < length; j++) { // catch exception types and rethrow
            newClass =
                ByteUtility.addBytes(newClass, (short) 0); // start_pc                 (fixed)
            if (propertyChangeFlag[i]) {
              newClass =
                  ByteUtility.addBytes(newClass, (short) 21); // end_pc                   (fixed)
              newClass =
                  ByteUtility.addBytes(newClass, (short) 22); // handler_pc               (fixed)
            } else {
              newClass =
                  ByteUtility.addBytes(newClass, (short) 19); // end_pc                   (fixed)
              newClass =
                  ByteUtility.addBytes(newClass, (short) 20); // handler_pc               (fixed)
            }
            newClass =
                ByteUtility.addBytes(
                    newClass, (short) excpIndex[i][j]); // catch_type               (variable)
          }
          // catch "exception" and trap it
          newClass = ByteUtility.addBytes(newClass, (short) 0); // start_pc                 (fixed)
          if (propertyChangeFlag[i]) {
            newClass =
                ByteUtility.addBytes(newClass, (short) 21); // end_pc                   (fixed)
            newClass =
                ByteUtility.addBytes(newClass, (short) 25); // handler_pc               (fixed)
          } else {
            newClass =
                ByteUtility.addBytes(newClass, (short) 19); // end_pc                   (fixed)
            newClass =
                ByteUtility.addBytes(newClass, (short) 23); // handler_pc               (fixed)
          }
          if (nonExceptionable) {
            newClass = ByteUtility.addBytes(newClass, (short) 26);
          } // catch_type               (fixed)
          else // or
          {
            newClass = ByteUtility.addBytes(newClass, (short) 23);
          } // catch_type               (fixed)
        } else {
          newClass = ByteUtility.addBytes(newClass, (short) 0);
        } // exception_table_length   (fixed)
        // attributes on the code attribute (none)
        newClass = ByteUtility.addBytes(newClass, (short) 0); // attribute_count          (fixed)
        // end code attribute

      } /* End for*/
      // Class Attributes (none for this)
      newClass = ByteUtility.addBytes(newClass, (short) 0); // attribute_count          (fixed)
      /* done */

      DebugLog.stdoutPrintln("adapterName: " + finalAdapterClassName, DebugLog.BSF_LOG_L3);
      DebugLog.stdoutPrintln(
          "cpCount: " + count + " = " + BASECPCOUNT + " + " + cpCount, DebugLog.BSF_LOG_L3);
      DebugLog.stdoutPrintln("methodCount: " + (lms.length + 1), DebugLog.BSF_LOG_L3);
      // output to disk class file
      /* ****************************************************************************************** */

      // now create the class and load it
      // return the Class.

      if (writeClassFile) {
        try {
          FileOutputStream fos =
              new FileOutputStream(WRITEDIRECTORY + finalAdapterClassName + ".class");
          fos.write(newClass);
          fos.close();
        } catch (IOException ex) {
          System.err.println(ex.getMessage());
          ex.printStackTrace();
        }

        try {
          Class ret = ldr.loadClass(finalAdapterClassName);
          DebugLog.stdoutPrintln(
              "EventAdapterGenerator: " + ret.getName() + " dynamically generated",
              DebugLog.BSF_LOG_L3);
          return ret;
        } catch (ClassNotFoundException ex) {
          System.err.println(ex.getMessage());
          ex.printStackTrace();
        }
      }

      try {
        Class ret = ldr.defineClass(finalAdapterClassName, newClass);
        DebugLog.stdoutPrintln(
            "EventAdapterGenerator: " + ret.getName() + " dynamically generated",
            DebugLog.BSF_LOG_L3);
        return ret;
      } catch (Exception ex) {
        System.err.println(ex.getMessage());
        ex.printStackTrace();
      }
    } else {
      System.err.println(
          "EventAdapterGenerator ListenerType invalid: listenerType = " + listenerType);
    }
    return null;
  }