Example #1
0
 private static STClass[] sodaTestCases() {
   STClass[] commonCases = commonTestCases();
   STClass[] collectionCases = collectionTestCases();
   STClass[] allCases = new STClass[commonCases.length + collectionCases.length];
   System.arraycopy(commonCases, 0, allCases, 0, commonCases.length);
   System.arraycopy(collectionCases, 0, allCases, commonCases.length, collectionCases.length);
   return allCases;
 }
 <T> T[] concat(T[] a, T[] b) {
   if ((b == null) || (b.length == 0)) {
     return a;
   }
   T[] r =
       (T[])
           java.lang.reflect.Array.newInstance(
               a.getClass().getComponentType(), a.length + b.length);
   System.arraycopy(a, 0, r, 0, a.length);
   System.arraycopy(b, 0, r, a.length, b.length);
   return r;
 }
 private JAXBContext newJAXBContext(final Class<?>... pClasses) throws JAXBException {
   Class<?>[] classList;
   final Class<?> clazz = getDeclaringClass();
   final XmlSeeAlso seeAlso = clazz.getAnnotation(XmlSeeAlso.class);
   if ((seeAlso != null) && (seeAlso.value().length > 0)) {
     final Class<?>[] seeAlsoClasses = seeAlso.value();
     classList = new Class<?>[seeAlsoClasses.length + pClasses.length];
     System.arraycopy(seeAlsoClasses, 0, classList, 0, seeAlsoClasses.length);
     System.arraycopy(pClasses, 0, classList, seeAlsoClasses.length, pClasses.length);
   } else {
     classList = pClasses;
   }
   return JAXBContext.newInstance(classList);
 }
Example #4
0
 /**
  * @generate serialEvent.xml
  * @webref serial:events
  * @usage web_application
  * @param event the port where new data is available
  */
 public void serialEvent(SerialPortEvent event) {
   if (event.getEventType() == SerialPortEvent.RXCHAR) {
     int toRead;
     try {
       while (0 < (toRead = port.getInputBufferBytesCount())) {
         // this method can be called from the context of another thread
         synchronized (buffer) {
           // read one byte at a time if the sketch is using serialEvent
           if (serialEventMethod != null) {
             toRead = 1;
           }
           // enlarge buffer if necessary
           if (buffer.length < inBuffer + toRead) {
             byte temp[] = new byte[buffer.length << 1];
             System.arraycopy(buffer, 0, temp, 0, inBuffer);
             buffer = temp;
           }
           // read an array of bytes and copy it into our buffer
           byte[] read = port.readBytes(toRead);
           System.arraycopy(read, 0, buffer, inBuffer, read.length);
           inBuffer += read.length;
         }
         if (serialEventMethod != null) {
           if ((0 < bufferUntilSize && bufferUntilSize <= inBuffer - readOffset)
               || (0 == bufferUntilSize && bufferUntilByte == buffer[inBuffer - 1])) {
             try {
               // serialEvent() is invoked in the context of the current (serial) thread
               // which means that serialization and atomic variables need to be used to
               // guarantee reliable operation (and better not draw() etc..)
               // serialAvailable() does not provide any real benefits over using
               // available() and read() inside draw - but this function has no
               // thread-safety issues since it's being invoked during pre in the context
               // of the Processing applet
               serialEventMethod.invoke(parent, this);
             } catch (Exception e) {
               System.err.println("Error, disabling serialEvent() for " + port.getPortName());
               System.err.println(e.getLocalizedMessage());
               serialEventMethod = null;
             }
           }
         }
         invokeSerialAvailable = true;
       }
     } catch (SerialPortException e) {
       throw new RuntimeException(
           "Error reading from serial port " + e.getPortName() + ": " + e.getExceptionType());
     }
   }
 }
  /**
   * Returns the clone of <code>o_</code>. It calls <code>o_.clone()</code>, if possible, and either
   * raises an exception or returns null if fails.
   *
   * @param raiseException_ set to true if one wishes to get exception instead of receiving null
   *     when this method fails to call <code>o_.clone()</code>.
   */
  public static Object clone(Object o_, boolean raiseException_) {
    if (o_ == null) return null;
    if (o_ instanceof String) return o_;

    try {
      if (o_ instanceof drcl.ObjectCloneable) return ((drcl.ObjectCloneable) o_).clone();
      if (o_.getClass().isArray()) {
        int length_ = Array.getLength(o_);
        Class componentType_ = o_.getClass().getComponentType();
        Object that_ = Array.newInstance(componentType_, length_);
        if (componentType_.isPrimitive()) System.arraycopy(o_, 0, that_, 0, length_);
        else {
          for (int i = 0; i < length_; i++)
            Array.set(that_, i, clone(Array.get(o_, i), raiseException_));
        }
        return that_;
      }
      Method m_ = o_.getClass().getMethod("clone", null);
      return m_.invoke(o_, null);
    } catch (Exception e_) {
      if (raiseException_) {
        Thread t_ = Thread.currentThread();
        t_.getThreadGroup().uncaughtException(t_, e_);
      }
      return null;
    }
  }
 private static void handleTileEntityPacket(Packet230ModLoader packet230modloader) {
   if (packet230modloader.dataInt == null || packet230modloader.dataInt.length < 5) {
     log("Bad TileEntityPacket received.");
   } else {
     int i = packet230modloader.dataInt[0];
     int j = packet230modloader.dataInt[1];
     int k = packet230modloader.dataInt[2];
     int l = packet230modloader.dataInt[3];
     int i1 = packet230modloader.dataInt[4];
     int ai[] = new int[packet230modloader.dataInt.length - 5];
     System.arraycopy(packet230modloader.dataInt, 5, ai, 0, packet230modloader.dataInt.length - 5);
     float af[] = packet230modloader.dataFloat;
     String as[] = packet230modloader.dataString;
     for (int j1 = 0; j1 < ModLoader.getLoadedMods().size(); j1++) {
       BaseMod basemod = (BaseMod) ModLoader.getLoadedMods().get(j1);
       if (!(basemod instanceof BaseModMp)) {
         continue;
       }
       BaseModMp basemodmp = (BaseModMp) basemod;
       if (basemodmp.getId() != i) {
         continue;
       }
       basemodmp.handleTileEntityPacket(j, k, l, i1, ai, af, as);
       break;
     }
   }
 }
Example #7
0
  /**
   * @generate Serial_readBytesUntil.xml
   * @webref serial:serial
   * @usage web_application
   * @param inByte character designated to mark the end of the data
   */
  public byte[] readBytesUntil(int inByte) {
    if (inBuffer == readOffset) {
      return null;
    }

    synchronized (buffer) {
      // look for needle in buffer
      int found = -1;
      for (int i = readOffset; i < inBuffer; i++) {
        if (buffer[i] == (byte) inByte) {
          found = i;
          break;
        }
      }
      if (found == -1) {
        return null;
      }

      int toCopy = found - readOffset + 1;
      byte[] dest = new byte[toCopy];
      System.arraycopy(buffer, readOffset, dest, 0, toCopy);
      readOffset += toCopy;
      if (inBuffer == readOffset) {
        inBuffer = 0;
        readOffset = 0;
      }
      return dest;
    }
  }
Example #8
0
 /**
  * attempt to invoke a Method with the given Object arguments, performing static method
  * auto-detection and automatic array compression
  */
 public static Object invokeMethod(Method m, Object[] o)
     throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
   Object obj;
   Object[] args;
   Class[] c = m.getParameterTypes();
   int num = (o == null) ? 0 : o.length;
   int len = -1;
   int a = -1;
   if (c != null) {
     len = c.length;
     for (int i = 0; i < len; i++) {
       if (c[i].isArray()) a = i;
     }
   }
   if (Modifier.isStatic(m.getModifiers())) {
     // static method
     obj = null;
     if (num > 0) {
       if (a < 0) {
         args = new Object[num];
         System.arraycopy(o, 0, args, 0, num);
       } else {
         // compress some of the arguments into array form
         args = new Object[len];
         if (a > 0) System.arraycopy(o, 0, args, 0, a);
         Object array = Array.newInstance(c[a].getComponentType(), num - len + 1);
         System.arraycopy(o, a, array, 0, num - len + 1);
         args[a] = array;
         if (a < len - 1) System.arraycopy(o, num - len + a + 1, args, a + 1, len - a - 1);
       }
     } else args = null;
   } else {
     // object method
     if (num > 0) obj = o[0];
     else {
       // invalid object method
       return null;
     }
     if (num > 1) {
       if (a < 0) {
         args = new Object[num - 1];
         System.arraycopy(o, 1, args, 0, num - 1);
       } else {
         // compress some of the arguments into array form
         args = new Object[len];
         if (a > 0) System.arraycopy(o, 1, args, 0, a);
         Object array = Array.newInstance(c[a].getComponentType(), num - len);
         System.arraycopy(o, a + 1, array, 0, num - len);
         args[a + 1] = array;
         if (a < len - 1) System.arraycopy(o, num - len + a + 1, args, a + 1, len - a - 1);
       }
     } else args = null;
   }
   return m.invoke(obj, args);
 }
Example #9
0
 /**
  * Returns the generic type information of an attribute.
  *
  * @param field the field representation of the attribute.
  * @return an array of types that are used to parameterize the attribute.
  */
 public static Class<?>[] getGenericTypes(Field field) {
   Type genericFieldType = field.getGenericType();
   if (!(genericFieldType instanceof ParameterizedType)) return null; // type is not generic
   ParameterizedType pType = (ParameterizedType) genericFieldType;
   Type[] args = pType.getActualTypeArguments();
   Class<?>[] types = new Class[args.length];
   System.arraycopy(args, 0, types, 0, args.length);
   return types;
 }
Example #10
0
      public int write(byte[] buffer, int offset, int length, boolean transform) {
        RawPacket pkt = rawPacketArray[0];
        if (pkt == null) pkt = new RawPacket();
        rawPacketArray[0] = pkt;

        byte[] pktBuf = pkt.getBuffer();
        if (pktBuf == null || pktBuf.length < length) {
          pktBuf = new byte[length];
          pkt.setBuffer(pktBuf);
        }
        System.arraycopy(buffer, offset, pktBuf, 0, length);
        pkt.setOffset(0);
        pkt.setLength(length);

        if (transform) {
          PacketTransformer packetTransformer =
              isControlStream ? rtcpPacketTransformer : rtpPacketTransformer;

          if (packetTransformer != null)
            rawPacketArray = packetTransformer.reverseTransform(rawPacketArray);
        }

        SourceTransferHandler transferHandler;
        PushSourceStream pushSourceStream;

        try {
          if (isControlStream) {
            transferHandler = controlTransferHandler;
            pushSourceStream = getControlInputStream();
          } else {
            transferHandler = dataTransferHandler;
            pushSourceStream = getDataInputStream();
          }
        } catch (IOException ioe) {
          throw new UndeclaredThrowableException(ioe);
        }

        for (int i = 0; i < rawPacketArray.length; i++) {
          RawPacket packet = rawPacketArray[i];

          // keep the first element for reuse
          if (i != 0) rawPacketArray[i] = null;

          if (packet != null) {
            if (isControlStream) pendingControlPacket = packet;
            else pendingDataPacket = packet;

            if (transferHandler != null) {
              transferHandler.transferData(pushSourceStream);
            }
          }
        }

        return length;
      }
Example #11
0
  protected static Object[] extractMockArguments(Object[] args) {
    int i = 7;

    if (args.length > i) {
      Object[] mockArgs = new Object[args.length - i];
      System.arraycopy(args, i, mockArgs, 0, mockArgs.length);
      return mockArgs;
    }

    return EMPTY_ARGS;
  }
Example #12
0
  /**
   * @generate Serial_readBytes.xml
   * @webref serial:serial
   * @usage web_application
   */
  public byte[] readBytes() {
    if (inBuffer == readOffset) {
      return null;
    }

    synchronized (buffer) {
      byte[] ret = new byte[inBuffer - readOffset];
      System.arraycopy(buffer, readOffset, ret, 0, ret.length);
      inBuffer = 0;
      readOffset = 0;
      return ret;
    }
  }
Example #13
0
  /**
   * Add a listener
   *
   * @param listener
   * @param highPriority true if the listener should be put on the front of the list, false if it
   *     should be added to the end.
   * @return true if the listener was added, false if it was already present
   */
  protected final boolean addListener(Object listener, boolean highPriority) {
    // bail if the listener is already added
    for (int i = 0; i < fListeners.length; i++) {
      if (fListeners[i] == listener) return false;
    }

    // make a new listener array, one element larger than the old one
    // and add the new listener to the end
    Object[] newArray = new Object[fListeners.length + 1];
    if (highPriority) {
      // add to front of list
      System.arraycopy(fListeners, 0, newArray, 1, fListeners.length);
      newArray[0] = listener;
    } else {
      // add to end of list
      System.arraycopy(fListeners, 0, newArray, 0, fListeners.length);
      newArray[fListeners.length] = listener;
    }

    // make it the active array
    fListeners = newArray;
    return true;
  }
Example #14
0
  public static <T> T mixin(T target, Class<?>... interfaces) {
    if (target == null) return null;

    // When request is
    final Class<?> targetClass = target.getClass();
    if (Arrays.stream(interfaces).allMatch(i -> i.isAssignableFrom(targetClass))) {
      return target;
    }

    Class[] classes;
    int addedIndex;
    if (Proxy.isProxyClass(targetClass)) {
      MixinProxyHandler<T> handler = ((MixinProxyHandler<T>) Proxy.getInvocationHandler(target));
      target = handler.getOriginal();
      Class[] originalInterfaces = handler.getProxyInterfaces();
      classes = new Class[originalInterfaces.length + interfaces.length];
      System.arraycopy(originalInterfaces, 0, classes, 0, originalInterfaces.length);
      addedIndex = originalInterfaces.length;
    } else {
      Class[] targetInterfaces = getAllInterfaces(targetClass);
      classes = new Class[targetInterfaces.length + interfaces.length];
      System.arraycopy(targetInterfaces, 0, classes, 0, targetInterfaces.length);
      addedIndex = targetInterfaces.length;
    }
    Arrays.asList(interfaces)
        .forEach(
            i ->
                Arrays.asList(i.getMethods())
                    .stream()
                    .filter(Method::isDefault)
                    .forEach(MixinUtils::getMethodHandle));

    System.arraycopy(interfaces, 0, classes, addedIndex, interfaces.length);

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    return (T) Proxy.newProxyInstance(cl, classes, new MixinProxyHandler(target, classes));
  }
Example #15
0
  public PGroupElementArray toElementArray(PGroupElementArray... arrays) {

    int total = 0;
    for (int i = 0; i < arrays.length; i++) {
      total += arrays[i].size();
    }

    PGroupElement[] res = new PGroupElement[total];
    int offset = 0;
    for (int i = 0; i < arrays.length; i++) {
      int len = arrays[i].size();
      System.arraycopy(arrays[i].elements(), 0, res, offset, len);
      offset += len;
    }
    return new BPGroupElementArray(this, res);
  }
Example #16
0
 /**
  * Unsupported command line interface.
  *
  * @param args The command line parameters.
  */
 public static void main(String[] args) throws Exception {
   if (args.length > 0 && args[0].equals("-Xjdb")) {
     String[] newargs = new String[args.length + 2];
     Class<?> c = Class.forName("com.redhat.ceylon.langtools.tools.example.debug.tty.TTY");
     Method method = c.getDeclaredMethod("main", new Class<?>[] {args.getClass()});
     method.setAccessible(true);
     System.arraycopy(args, 1, newargs, 3, args.length - 1);
     newargs[0] = "-connect";
     newargs[1] =
         "com.redhat.ceylon.langtools.jdi.CommandLineLaunch:options=-esa -ea:com.redhat.ceylon.langtools.tools...";
     newargs[2] = "com.redhat.ceylon.langtools.tools.javac.Main";
     method.invoke(null, new Object[] {newargs});
   } else {
     System.exit(compile(args));
   }
 }
Example #17
0
  public R invoke(Object[] arguments) throws MethodInvokeFailedException {
    int expectedNumArgs = method.getParameterTypes().length;
    R result;

    if ((arguments.length != expectedNumArgs && !method.isVarArgs())
        || (arguments.length < expectedNumArgs
            && (arguments.length == expectedNumArgs - 1 && !method.isVarArgs()))) {
      throw new MethodInvokeFailedException(
          String.format(
              "Incorrect number of arguments for method specified invoking %1$s (expected %2$s; received: %3$s).",
              method.getName(), expectedNumArgs, arguments.length));
    }

    Object[] args = null;
    try {
      if (method.isVarArgs()) {
        args = new Object[method.getParameterTypes().length];

        // Copy over fixed arguments
        for (int i = 0; i < args.length - 1; i++) {
          args[i] = arguments[i];
        }

        // Prepare variable argument for last position of arguments array
        Class type =
            method.getParameterTypes()[method.getParameterTypes().length - 1].getComponentType();
        Object[] varArgs =
            (Object[])
                java.lang.reflect.Array.newInstance(type, (arguments.length - expectedNumArgs) + 1);
        System.arraycopy(arguments, args.length - 1, varArgs, 0, varArgs.length);
        args[args.length - 1] = varArgs;
        result = (R) method.invoke(target, args);
      } else {
        //				args = validateTypes(arguments, method.getParameterTypes());
        args = arguments;
        result = (R) method.invoke(target, args);
      }
    } catch (Exception e) {
      throw new MethodInvokeFailedException(
          String.format(
              "Exception thrown invoking %1$s with arguments %2$s.",
              method.getName(), java.util.Arrays.deepToString(args)),
          e);
    }
    return result;
  }
Example #18
0
  /**
   *
   *
   * <h3>Advanced</h3>
   *
   * Grab whatever is in the serial buffer, and stuff it into a byte buffer passed in by the user.
   * This is more memory/time efficient than readBytes() returning a byte[] array.
   *
   * <p>Returns an int for how many bytes were read. If more bytes are available than can fit into
   * the byte array, only those that will fit are read.
   */
  public int readBytes(byte[] dest) {
    if (inBuffer == readOffset) {
      return 0;
    }

    synchronized (buffer) {
      int toCopy = inBuffer - readOffset;
      if (dest.length < toCopy) {
        toCopy = dest.length;
      }
      System.arraycopy(buffer, readOffset, dest, 0, toCopy);
      readOffset += toCopy;
      if (inBuffer == readOffset) {
        inBuffer = 0;
        readOffset = 0;
      }
      return toCopy;
    }
  }
Example #19
0
  static Object js_createAdpter(Context cx, Scriptable scope, Object[] args) {
    int N = args.length;
    if (N == 0) {
      throw ScriptRuntime.typeError0("msg.adapter.zero.args");
    }

    Class superClass = null;
    Class[] intfs = new Class[N - 1];
    int interfaceCount = 0;
    for (int i = 0; i != N - 1; ++i) {
      Object arg = args[i];
      if (!(arg instanceof NativeJavaClass)) {
        throw ScriptRuntime.typeError2(
            "msg.not.java.class.arg", String.valueOf(i), ScriptRuntime.toString(arg));
      }
      Class c = ((NativeJavaClass) arg).getClassObject();
      if (!c.isInterface()) {
        if (superClass != null) {
          throw ScriptRuntime.typeError2("msg.only.one.super", superClass.getName(), c.getName());
        }
        superClass = c;
      } else {
        intfs[interfaceCount++] = c;
      }
    }

    if (superClass == null) superClass = ScriptRuntime.ObjectClass;

    Class[] interfaces = new Class[interfaceCount];
    System.arraycopy(intfs, 0, interfaces, 0, interfaceCount);
    Scriptable obj = ScriptRuntime.toObject(cx, scope, args[N - 1]);

    Class adapterClass = getAdapterClass(scope, superClass, interfaces, obj);

    Class[] ctorParms = {ScriptRuntime.ContextFactoryClass, ScriptRuntime.ScriptableClass};
    Object[] ctorArgs = {cx.getFactory(), obj};
    try {
      Object adapter = adapterClass.getConstructor(ctorParms).newInstance(ctorArgs);
      return getAdapterSelf(adapterClass, adapter);
    } catch (Exception ex) {
      throw Context.throwAsScriptRuntimeEx(ex);
    }
  }
Example #20
0
      @Override
      public int read(byte[] buffer, int offset, int length) throws IOException {

        RawPacket pendingPacket;
        if (isControlStream) {
          pendingPacket = pendingControlPacket;
        } else {
          pendingPacket = pendingDataPacket;
        }
        int bytesToRead = 0;
        byte[] pendingPacketBuffer = pendingPacket.getBuffer();
        if (pendingPacketBuffer != null) {
          int pendingPacketLength = pendingPacket.getLength();
          bytesToRead = length > pendingPacketLength ? pendingPacketLength : length;
          System.arraycopy(
              pendingPacketBuffer, pendingPacket.getOffset(), buffer, offset, bytesToRead);
        }
        return bytesToRead;
      }
Example #21
0
  /**
   *
   *
   * <h3>Advanced</h3>
   *
   * Return a byte array of anything that's in the serial buffer up to the specified maximum number
   * of bytes. Not particularly memory/speed efficient, because it creates a byte array on each
   * read, but it's easier to use than readBytes(byte b[]) (see below).
   *
   * @param max the maximum number of bytes to read
   */
  public byte[] readBytes(int max) {
    if (inBuffer == readOffset) {
      return null;
    }

    synchronized (buffer) {
      int length = inBuffer - readOffset;
      if (length > max) length = max;
      byte[] ret = new byte[length];
      System.arraycopy(buffer, readOffset, ret, 0, length);

      readOffset += length;
      if (inBuffer == readOffset) {
        inBuffer = 0;
        readOffset = 0;
      }
      return ret;
    }
  }
 /**
  * Creates a new AgentMBeanServerConnectionFactory
  *
  * @param builder The AgentMBeanServerConnectionFactory builder
  */
 protected AgentMBeanServerConnectionFactory(Builder builder) {
   this.channel = builder.channel;
   this.remoteAddress =
       builder.remoteAddress == null ? this.channel.getRemoteAddress() : builder.remoteAddress;
   this.timeout = builder.timeout;
   this.listener = builder.listener;
   this.domain = builder.domain;
   if ("DefaultDomain".equals(domain)) {
     domainInfoData = new byte[] {0};
   } else {
     byte[] domainBytes = domain.getBytes();
     domainInfoData = new byte[domainBytes.length + 1];
     domainInfoData[0] = (byte) domainBytes.length;
     System.arraycopy(domainBytes, 0, domainInfoData, 1, domainBytes.length);
   }
   if (channel.getPipeline().get(getClass().getSimpleName()) == null) {
     this.channel.getPipeline().addFirst(getClass().getSimpleName(), responseHandler);
     //			LoggingHandler logg = new LoggingHandler(InternalLogLevel.ERROR, true);
     //			this.channel.getPipeline().addFirst("logger", logg);
   }
 }
Example #23
0
  /**
   * Invoke the user defined static method in the nested "Duck" class so that the user can define
   * convenience methods on the config beans.
   */
  Object invokeDuckMethod(Method method, Object proxy, Object[] args) throws Exception {
    Method duckMethod = model.getDuckMethod(method);

    Object[] duckArgs;
    if (args == null) {
      duckArgs = new Object[] {proxy};
    } else {
      duckArgs = new Object[args.length + 1];
      duckArgs[0] = proxy;
      System.arraycopy(args, 0, duckArgs, 1, args.length);
    }

    try {
      return duckMethod.invoke(null, duckArgs);
    } catch (InvocationTargetException e) {
      Throwable t = e.getTargetException();
      if (t instanceof Exception) throw (Exception) t;
      if (t instanceof Error) throw (Error) t;
      throw e;
    }
  }
 public static void main(String[] args) {
   if (args.length < 3) {
     System.out.println(
         "Usage: java CleanupConstants <OS className> <class source> <src path1> <src path2>");
     return;
   }
   try {
     CleanupConstants gen = new CleanupConstants();
     String clazzName = args[0];
     String classSource = args[1];
     String[] sourcePath = new String[args.length - 2];
     System.arraycopy(args, 2, sourcePath, 0, sourcePath.length);
     Class<?> clazz = Class.forName(clazzName);
     gen.setSourcePath(sourcePath);
     gen.setClassSourcePath(classSource);
     gen.generate(new ReflectClass(clazz));
   } catch (Exception e) {
     System.out.println("Problem");
     e.printStackTrace(System.out);
   }
 }
Example #25
0
  /**
   *
   *
   * <h3>Advanced</h3>
   *
   * If dest[] is not big enough, then -1 is returned, and an error message is printed on the
   * console. If nothing is in the buffer, zero is returned. If 'interesting' byte is not in the
   * buffer, then 0 is returned.
   *
   * @param dest passed in byte array to be altered
   */
  public int readBytesUntil(int inByte, byte[] dest) {
    if (inBuffer == readOffset) {
      return 0;
    }

    synchronized (buffer) {
      // look for needle in buffer
      int found = -1;
      for (int i = readOffset; i < inBuffer; i++) {
        if (buffer[i] == (byte) inByte) {
          found = i;
          break;
        }
      }
      if (found == -1) {
        return 0;
      }

      // check if bytes to copy fit in dest
      int toCopy = found - readOffset + 1;
      if (dest.length < toCopy) {
        System.err.println(
            "The buffer passed to readBytesUntil() is to small "
                + "to contain "
                + toCopy
                + " bytes up to and including "
                + "char "
                + (byte) inByte);
        return -1;
      }
      System.arraycopy(buffer, readOffset, dest, 0, toCopy);
      readOffset += toCopy;
      if (inBuffer == readOffset) {
        inBuffer = 0;
        readOffset = 0;
      }
      return toCopy;
    }
  }
 /**
  * Deserializes an array of arguments from a byte array
  *
  * @param bytes The byte array containing the serialized arguments
  * @return an object array
  */
 public static Object[] getInput(byte[] bytes) {
   if (bytes.length == 0 || (bytes.length == 1 && bytes[0] == 0)) return new Object[0];
   ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
   ObjectInputStream ois = null;
   GZIPInputStream gzis = null;
   Object[] args = null;
   try {
     gzis = new GZIPInputStream(bais);
     ois = new ObjectInputStream(gzis);
     Object obj = ois.readObject();
     if (obj.getClass().isArray()) {
       args = new Object[Array.getLength(obj)];
       System.arraycopy(obj, 0, args, 0, args.length);
     } else {
       args = new Object[] {obj};
     }
     return args;
   } catch (Exception ex) {
     throw new RuntimeException("Failed to decode MBeanServerConnection Invocation arguments", ex);
   } finally {
     try {
       bais.close();
     } catch (Exception ex) {
       /* No Op */
     }
     if (ois != null)
       try {
         ois.close();
       } catch (Exception ex) {
         /* No Op */
       }
     if (gzis != null)
       try {
         gzis.close();
       } catch (Exception ex) {
         /* No Op */
       }
   }
 }
  public static int[] createInterceptors(
      InjectManager manager,
      ArrayList<Interceptor> beans,
      int[] indexList,
      InterceptionType type,
      Annotation... bindings) {
    List<Interceptor<?>> interceptors;

    if (bindings != null && bindings.length > 0) {
      interceptors = manager.resolveInterceptors(type, bindings);
    } else interceptors = new ArrayList<Interceptor<?>>();

    int offset = 0;

    if (indexList == null) {
      indexList = new int[interceptors.size()];
    } else {
      offset = indexList.length;

      int[] newIndexList = new int[indexList.length + interceptors.size()];
      System.arraycopy(indexList, 0, newIndexList, 0, indexList.length);
      indexList = newIndexList;
    }

    for (int i = 0; i < interceptors.size(); i++) {
      Interceptor<?> interceptor = interceptors.get(i);

      int index = beans.indexOf(interceptor);
      if (index >= 0) indexList[offset + i] = index;
      else {
        indexList[offset + i] = beans.size();
        beans.add(interceptor);
      }
    }

    return indexList;
  }
Example #28
0
  /**
   * Analyze class fields and fill in "voSetterMethods","voGetterMethods","indexes",reverseIndexes"
   * attributes.
   *
   * @param prefix e.g. "attrx.attry."
   * @param parentMethods getter methods of parent v.o.
   * @param classType class to analyze
   */
  private void analyzeClassFields(String prefix, Method[] parentMethods, Class classType) {
    try {
      if (prefix.split("\\.").length > ClientSettings.MAX_NR_OF_LOOPS_IN_ANALYZE_VO) return;

      // retrieve all getter and setter methods defined in the specified value object...
      String attributeName = null;
      Method[] methods = classType.getMethods();
      String aName = null;
      for (int i = 0; i < methods.length; i++) {
        attributeName = methods[i].getName();

        if (attributeName.startsWith("get")
            && methods[i].getParameterTypes().length == 0
            && ValueObject.class.isAssignableFrom(methods[i].getReturnType())) {
          aName = getAttributeName(attributeName, classType);
          Method[] newparentMethods = new Method[parentMethods.length + 1];
          System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
          newparentMethods[parentMethods.length] = methods[i];
          analyzeClassFields(prefix + aName + ".", newparentMethods, methods[i].getReturnType());
        }

        if (attributeName.startsWith("get")
            && methods[i].getParameterTypes().length == 0
            && (methods[i].getReturnType().equals(String.class)
                || methods[i].getReturnType().equals(Long.class)
                || methods[i].getReturnType().equals(Long.TYPE)
                || methods[i].getReturnType().equals(Float.class)
                || methods[i].getReturnType().equals(Float.TYPE)
                || methods[i].getReturnType().equals(Short.class)
                || methods[i].getReturnType().equals(Short.TYPE)
                || methods[i].getReturnType().equals(Double.class)
                || methods[i].getReturnType().equals(Double.TYPE)
                || methods[i].getReturnType().equals(BigDecimal.class)
                || methods[i].getReturnType().equals(java.util.Date.class)
                || methods[i].getReturnType().equals(java.sql.Date.class)
                || methods[i].getReturnType().equals(java.sql.Timestamp.class)
                || methods[i].getReturnType().equals(Integer.class)
                || methods[i].getReturnType().equals(Integer.TYPE)
                || methods[i].getReturnType().equals(Character.class)
                || methods[i].getReturnType().equals(Boolean.class)
                || methods[i].getReturnType().equals(boolean.class)
                || methods[i].getReturnType().equals(ImageIcon.class)
                || methods[i].getReturnType().equals(Icon.class)
                || methods[i].getReturnType().equals(byte[].class)
                || methods[i].getReturnType().equals(Object.class)
                || ValueObject.class.isAssignableFrom(methods[i].getReturnType()))) {
          attributeName = getAttributeName(attributeName, classType);
          //          try {
          //            if
          // (classType.getMethod("set"+attributeName.substring(0,1).toUpperCase()+attributeName.substring(1),new Class[]{methods[i].getReturnType()})!=null)
          Method[] newparentMethods = new Method[parentMethods.length + 1];
          System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
          newparentMethods[parentMethods.length] = methods[i];
          voGetterMethods.put(prefix + attributeName, newparentMethods);
          //          } catch (NoSuchMethodException ex) {
          //          }
        } else if (attributeName.startsWith("is")
            && methods[i].getParameterTypes().length == 0
            && (methods[i].getReturnType().equals(Boolean.class)
                || methods[i].getReturnType().equals(boolean.class))) {
          attributeName = getAttributeName(attributeName, classType);
          Method[] newparentMethods = new Method[parentMethods.length + 1];
          System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
          newparentMethods[parentMethods.length] = methods[i];
          voGetterMethods.put(prefix + attributeName, newparentMethods);
        } else if (attributeName.startsWith("set") && methods[i].getParameterTypes().length == 1) {
          attributeName = getAttributeName(attributeName, classType);
          try {
            if (classType.getMethod(
                    "get"
                        + attributeName.substring(0, 1).toUpperCase()
                        + attributeName.substring(1),
                    new Class[0])
                != null) {
              Method[] newparentMethods = new Method[parentMethods.length + 1];
              System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
              newparentMethods[parentMethods.length] = methods[i];
              voSetterMethods.put(prefix + attributeName, newparentMethods);
            }
          } catch (NoSuchMethodException ex) {
            try {
              if (classType.getMethod(
                      "is"
                          + attributeName.substring(0, 1).toUpperCase()
                          + attributeName.substring(1),
                      new Class[0])
                  != null) {
                Method[] newparentMethods = new Method[parentMethods.length + 1];
                System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length);
                newparentMethods[parentMethods.length] = methods[i];
                voSetterMethods.put(prefix + attributeName, newparentMethods);
              }
            } catch (NoSuchMethodException exx) {
            }
          }
        }
      }

      // fill in indexes with the colProperties indexes first; after them, it will be added the
      // other indexes (of attributes not mapped with grid column...)
      HashSet alreadyAdded = new HashSet();
      int i = 0;
      for (i = 0; i < colProperties.length; i++) {
        indexes.put(new Integer(i), colProperties[i].getColumnName());
        reverseIndexes.put(colProperties[i].getColumnName(), new Integer(i));
        alreadyAdded.add(colProperties[i].getColumnName());
      }
      Enumeration en = voGetterMethods.keys();
      while (en.hasMoreElements()) {
        attributeName = en.nextElement().toString();
        if (!alreadyAdded.contains(attributeName)) {
          indexes.put(new Integer(i), attributeName);
          reverseIndexes.put(attributeName, new Integer(i));
          i++;
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
 /**
  * On a Type Variable (typeVar extends C_0 & I_1 & I_2 & etc), will return an array containing
  * I_1 and I_2.
  *
  * @return other bounds for this type, these bounds can only be only interfaces as the JLS says,
  *     empty array if no other bound declared.
  */
 public Type[] interfaceBounds() {
   Type[] interfaceBounds = new Type[typeVariable.getBounds().length - 1];
   System.arraycopy(
       typeVariable.getBounds(), 1, interfaceBounds, 0, typeVariable.getBounds().length - 1);
   return interfaceBounds;
 }
Example #30
0
  static Object js_createAdapter(Context cx, Scriptable scope, Object[] args) {
    int N = args.length;
    if (N == 0) {
      throw ScriptRuntime.typeError0("msg.adapter.zero.args");
    }

    // Expected arguments:
    // Any number of NativeJavaClass objects representing the super-class
    // and/or interfaces to implement, followed by one NativeObject providing
    // the implementation, followed by any number of arguments to pass on
    // to the (super-class) constructor.

    int classCount;
    for (classCount = 0; classCount < N - 1; classCount++) {
      Object arg = args[classCount];
      // We explicitly test for NativeObject here since checking for
      // instanceof ScriptableObject or !(instanceof NativeJavaClass)
      // would fail for a Java class that isn't found in the class path
      // as NativeJavaPackage extends ScriptableObject.
      if (arg instanceof NativeObject) {
        break;
      }
      if (!(arg instanceof NativeJavaClass)) {
        throw ScriptRuntime.typeError2(
            "msg.not.java.class.arg", String.valueOf(classCount), ScriptRuntime.toString(arg));
      }
    }
    Class<?> superClass = null;
    Class<?>[] intfs = new Class[classCount];
    int interfaceCount = 0;
    for (int i = 0; i < classCount; ++i) {
      Class<?> c = ((NativeJavaClass) args[i]).getClassObject();
      if (!c.isInterface()) {
        if (superClass != null) {
          throw ScriptRuntime.typeError2("msg.only.one.super", superClass.getName(), c.getName());
        }
        superClass = c;
      } else {
        intfs[interfaceCount++] = c;
      }
    }

    if (superClass == null) {
      superClass = ScriptRuntime.ObjectClass;
    }

    Class<?>[] interfaces = new Class[interfaceCount];
    System.arraycopy(intfs, 0, interfaces, 0, interfaceCount);
    // next argument is implementation, must be scriptable
    Scriptable obj = ScriptableObject.ensureScriptable(args[classCount]);

    Class<?> adapterClass = getAdapterClass(scope, superClass, interfaces, obj);
    Object adapter;

    int argsCount = N - classCount - 1;
    try {
      if (argsCount > 0) {
        // Arguments contain parameters for super-class constructor.
        // We use the generic Java method lookup logic to find and
        // invoke the right constructor.
        Object[] ctorArgs = new Object[argsCount + 2];
        ctorArgs[0] = obj;
        ctorArgs[1] = cx.getFactory();
        System.arraycopy(args, classCount + 1, ctorArgs, 2, argsCount);
        // TODO: cache class wrapper?
        NativeJavaClass classWrapper = new NativeJavaClass(scope, adapterClass, true);
        NativeJavaMethod ctors = classWrapper.members.ctors;
        int index = ctors.findCachedFunction(cx, ctorArgs);
        if (index < 0) {
          String sig = NativeJavaMethod.scriptSignature(args);
          throw Context.reportRuntimeError2("msg.no.java.ctor", adapterClass.getName(), sig);
        }

        // Found the constructor, so try invoking it.
        adapter = NativeJavaClass.constructInternal(ctorArgs, ctors.methods[index]);
      } else {
        Class<?>[] ctorParms = {ScriptRuntime.ScriptableClass, ScriptRuntime.ContextFactoryClass};
        Object[] ctorArgs = {obj, cx.getFactory()};
        adapter = adapterClass.getConstructor(ctorParms).newInstance(ctorArgs);
      }

      Object self = getAdapterSelf(adapterClass, adapter);
      // Return unwrapped JavaAdapter if it implements Scriptable
      if (self instanceof Wrapper) {
        Object unwrapped = ((Wrapper) self).unwrap();
        if (unwrapped instanceof Scriptable) {
          if (unwrapped instanceof ScriptableObject) {
            ScriptRuntime.setObjectProtoAndParent((ScriptableObject) unwrapped, scope);
          }
          return unwrapped;
        }
      }
      return self;
    } catch (Exception ex) {
      throw Context.throwAsScriptRuntimeEx(ex);
    }
  }