Beispiel #1
0
  /**
   * Determines if a child node object is accepting.
   *
   * @param nodeObj an Object
   * @return if {@code nodeObj} is either an MDAGNode or a SimplifiedMDAGNode, true if the node is
   *     accepting, false otherwise throws IllegalArgumentException if {@code nodeObj} is not an
   *     MDAGNode or SimplifiedMDAGNode
   */
  private static boolean isAcceptNode(Object nodeObj) {
    if (nodeObj != null) {
      Class nodeObjClass = nodeObj.getClass();

      if (nodeObjClass.equals(MDAGNode.class)) return ((MDAGNode) nodeObj).isAcceptNode();
      else if (nodeObjClass.equals(SimpleMDAGNode.class))
        return ((SimpleMDAGNode) nodeObj).isAcceptNode();
    }

    throw new IllegalArgumentException("Argument is not an MDAGNode or SimpleMDAGNode");
  }
Beispiel #2
0
  /**
   * Generates a method called "super$methodName()" which can be called from JavaScript that is
   * equivalent to calling "super.methodName()" from Java. Eventually, this may be supported
   * directly in JavaScript.
   */
  private static void generateSuper(
      ClassFileWriter cfw,
      String genName,
      String superName,
      String methodName,
      String methodSignature,
      Class<?>[] parms,
      Class<?> returnType) {
    cfw.startMethod("super$" + methodName, methodSignature, ClassFileWriter.ACC_PUBLIC);

    // push "this"
    cfw.add(ByteCode.ALOAD, 0);

    // push the rest of the parameters.
    int paramOffset = 1;
    for (Class<?> parm : parms) {
      paramOffset += generatePushParam(cfw, paramOffset, parm);
    }

    // call the superclass implementation of the method.
    cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, methodName, methodSignature);

    // now, handle the return type appropriately.
    Class<?> retType = returnType;
    if (!retType.equals(Void.TYPE)) {
      generatePopResult(cfw, retType);
    } else {
      cfw.add(ByteCode.RETURN);
    }
    cfw.stopMethod((short) (paramOffset + 1));
  }
 /**
  * Generate a {@link DynamicEntity} from {@link
  * com.impetus.kundera.metadata.model.EntityMetadata}.
  *
  * @param entityMetadata metadata from Kundera ({@link
  *     com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata}).
  * @param id entity id.
  * @return a fresh new {@link DynamicEntity}
  * @throws com.impetus.kundera.KunderaException if id is not of type {@link String}.
  * @see DynamicEntity
  */
 public static DynamicEntity createDynamicEntity(EntityMetadata entityMetadata, Object id) {
   Class idClazz = entityMetadata.getIdAttribute().getJavaType();
   if (!(idClazz.equals(String.class))) {
     throw new KunderaException("Id attribute must be of type " + String.class);
   }
   return createDynamicEntity((String) id);
 }
Beispiel #4
0
 private static Class[] getValidPrimitiveTypes(Class type) {
   if (type.equals(long.class))
     return new Class[] {
       GLintptrARB.class,
       GLuint.class,
       GLintptr.class,
       GLsizeiptrARB.class,
       GLsizeiptr.class,
       GLint64EXT.class,
       GLuint64EXT.class
     };
   else if (type.equals(int.class))
     return new Class[] {
       GLbitfield.class, GLenum.class, GLhandleARB.class, GLint.class, GLuint.class, GLsizei.class
     };
   else if (type.equals(double.class)) return new Class[] {GLclampd.class, GLdouble.class};
   else if (type.equals(float.class)) return new Class[] {GLclampf.class, GLfloat.class};
   else if (type.equals(short.class))
     return new Class[] {GLhalf.class, GLshort.class, GLushort.class};
   else if (type.equals(byte.class))
     return new Class[] {GLbyte.class, GLcharARB.class, GLchar.class, GLubyte.class};
   else if (type.equals(boolean.class)) return new Class[] {GLboolean.class};
   else if (type.equals(void.class)) return new Class[] {GLvoid.class};
   else return new Class[] {};
 }
Beispiel #5
0
  /**
   * Examines a property's type to see which method should be used to parse the property's value.
   *
   * @param desc The description of the property
   * @param value The value of the XML attribute containing the prop value
   * @return The value stored in the element
   * @throws IOException If there is an error reading the document
   */
  public Object getObjectValue(PropertyDescriptor desc, String value) throws IOException {
    // Find out what kind of property it is
    Class type = desc.getPropertyType();

    // If it's an array, get the base type
    if (type.isArray()) {
      type = type.getComponentType();
    }

    // For native types, object wrappers for natives, and strings, use the
    // basic parse routine
    if (type.equals(Integer.TYPE)
        || type.equals(Long.TYPE)
        || type.equals(Short.TYPE)
        || type.equals(Byte.TYPE)
        || type.equals(Boolean.TYPE)
        || type.equals(Float.TYPE)
        || type.equals(Double.TYPE)
        || Integer.class.isAssignableFrom(type)
        || Long.class.isAssignableFrom(type)
        || Short.class.isAssignableFrom(type)
        || Byte.class.isAssignableFrom(type)
        || Boolean.class.isAssignableFrom(type)
        || Float.class.isAssignableFrom(type)
        || Double.class.isAssignableFrom(type)) {
      return parseBasicType(type, value);
    } else if (String.class.isAssignableFrom(type)) {
      return value;
    } else if (java.util.Date.class.isAssignableFrom(type)) {
      // If it's a date, use the date parser
      return parseDate(value, JOXDateHandler.determineDateFormat());
    } else {
      return null;
    }
  }
Beispiel #6
0
 public String getAutoTypeFromAnnotation(AnnotationMirror annotation) {
   Class annotation_class = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType());
   if (annotation_class.equals(GLint.class)) return "GL11.GL_INT";
   else if (annotation_class.equals(GLbyte.class)) return "GL11.GL_BYTE";
   else if (annotation_class.equals(GLshort.class)) return "GL11.GL_SHORT";
   if (annotation_class.equals(GLuint.class)) return "GL11.GL_UNSIGNED_INT";
   else if (annotation_class.equals(GLubyte.class)) return "GL11.GL_UNSIGNED_BYTE";
   else if (annotation_class.equals(GLushort.class)) return "GL11.GL_UNSIGNED_SHORT";
   else if (annotation_class.equals(GLfloat.class)) return "GL11.GL_FLOAT";
   else if (annotation_class.equals(GLdouble.class)) return "GL11.GL_DOUBLE";
   else return null;
 }
    /**
     * 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);
        }
      }
    }
Beispiel #8
0
  // 1: int;2: long; 3: byte; 4: boolean; 5: character;
  // 6: short; 7: float; 8: double
  private static void writePrimitiveArray(
      Class componentType, Object array, int length, OutputStream os) throws IOException {

    if (componentType.equals(Integer.TYPE)) {
      int[] ints = (int[]) array;
      os.write(1);
      for (int i = 0; i < length; i++) {
        PDataStream.writeInt(ints[i], os);
      }
    } else if (componentType.equals(Long.TYPE)) {
      os.write(2);
      long[] longs = (long[]) array;
      for (int i = 0; i < length; i++) {
        PDataStream.writeLong(longs[i], os);
      }
    } else if (componentType.equals(Byte.TYPE)) {
      os.write(3);
      os.write((byte[]) array);
    } else if (componentType.equals(Boolean.TYPE)) {
      os.write(4);
      boolean[] booleans = (boolean[]) array;
      for (int i = 0; i < length; i++) {
        PDataStream.writeBoolean(booleans[i], os);
      }
    } else if (componentType.equals(Character.TYPE)) {
      os.write(5);
      char[] chars = (char[]) array;
      for (int i = 0; i < length; i++) {
        PDataStream.writeChar(chars[i], os);
      }
    } else if (componentType.equals(Short.TYPE)) {
      os.write(6);
      short[] shorts = (short[]) array;
      for (int i = 0; i < length; i++) {
        PDataStream.writeShort(shorts[i], os);
      }
    } else if (componentType.equals(Float.TYPE)) {
      os.write(7);
      float[] floats = (float[]) array;
      for (int i = 0; i < length; i++) {
        PDataStream.writeFloat(floats[i], os);
      }
    } else if (componentType.equals(Double.TYPE)) {
      os.write(8);
      double[] doubles = (double[]) array;
      for (int i = 0; i < length; i++) {
        PDataStream.writeDouble(doubles[i], os);
      }
    } else {
      throw new IllegalArgumentException("Unsupported Primitive Type: " + componentType);
    }
  }
 /**
  * Find the class for the projection
  *
  * @param proj projection
  * @return corresponding ProjectionClass (or null if not found)
  */
 private ProjectionClass findProjectionClass(Projection proj) {
   Class want = proj.getClass();
   ComboBoxModel projClassList = projClassCB.getModel();
   for (int i = 0; i < projClassList.getSize(); i++) {
     ProjectionClass pc = (ProjectionClass) projClassList.getElementAt(i);
     if (want.equals(pc.projClass)) {
       return pc;
     }
   }
   return null;
 }
Beispiel #10
0
 // only if this is an object (not primitive) and non null!
 private static void writeRealObject(Object value, Class vClass, OutputStream os)
     throws IOException {
   try {
     if (vClass.equals(String.class)) {
       os.write(0);
       PDataStream.writeUTF((String) value, os);
     } else if (vClass.equals(Integer.class)) {
       os.write(1);
       PDataStream.writeInt(((Integer) value).intValue(), os);
     } else if (vClass.equals(Long.class)) {
       os.write(2);
       PDataStream.writeLong(((Long) value).longValue(), os);
     } else if (vClass.equals(Byte.class)) {
       os.write(3);
       os.write(((Byte) value).byteValue());
     } else if (vClass.equals(Boolean.class)) {
       os.write(4);
       PDataStream.writeBoolean(((Boolean) value).booleanValue(), os);
     } else if (vClass.equals(Character.class)) {
       os.write(5);
       PDataStream.writeChar(((Character) value).charValue(), os);
     } else if (vClass.equals(Short.class)) {
       os.write(6);
       PDataStream.writeShort(((Short) value).shortValue(), os);
     } else if (vClass.equals(Float.class)) {
       os.write(7);
       PDataStream.writeFloat(((Float) value).floatValue(), os);
     } else if (vClass.equals(Double.class)) {
       os.write(8);
       PDataStream.writeDouble(((Double) value).doubleValue(), os);
     } else if (Externalizable.class.isAssignableFrom(vClass)) {
       os.write(11);
       String name = vClass.getName();
       PDataStream.writeUTF(name, os);
       Externalizable tmp = (Externalizable) value;
       tmp.writeObject(os);
     } else {
       os.write(12);
       ObjectOutputStream out = new ObjectOutputStream(os);
       out.writeObject(value);
     }
   } catch (Exception exc) {
     throw new IOException(exc.toString());
   }
 }
Beispiel #11
0
  /**
   * @param aContainer
   * @param aComponentClass
   * @return
   */
  private static Component findComponent(
      final Container aContainer, final Class<? extends Component> aComponentClass) {
    Component result = null;

    final int cnt = aContainer.getComponentCount();
    for (int i = 0; (result == null) && (i < cnt); i++) {
      final Component comp = aContainer.getComponent(i);
      if (aComponentClass.equals(comp.getClass())) {
        result = comp;
      } else if (comp instanceof Container) {
        result = findComponent((Container) comp, aComponentClass);
      }
    }
    return result;
  }
Beispiel #12
0
  /**
   * Examines a property's type to see which method should be used to parse the property's value.
   *
   * @param desc The description of the property
   * @param element The XML element containing the property value
   * @return The value stored in the element
   * @throws IOException If there is an error reading the document
   */
  public Object getObjectValue(PropertyDescriptor desc, Element element) throws IOException {
    // Find out what kind of property it is
    Class type = desc.getPropertyType();

    // If it's an array, get the base type
    if (type.isArray()) {
      type = type.getComponentType();
    }

    // For native types, object wrappers for natives, and strings, use the
    // basic parse routine
    if (type.equals(Integer.TYPE)
        || type.equals(Long.TYPE)
        || type.equals(Short.TYPE)
        || type.equals(Byte.TYPE)
        || type.equals(Boolean.TYPE)
        || type.equals(Float.TYPE)
        || type.equals(Double.TYPE)
        || Integer.class.isAssignableFrom(type)
        || Long.class.isAssignableFrom(type)
        || Short.class.isAssignableFrom(type)
        || Byte.class.isAssignableFrom(type)
        || Boolean.class.isAssignableFrom(type)
        || Float.class.isAssignableFrom(type)
        || Double.class.isAssignableFrom(type)
        || String.class.isAssignableFrom(type)) {
      return readBasicType(type, element);
    } else if (java.util.Date.class.isAssignableFrom(type)) {
      // If it's a date, use the date parser
      return readDate(element);
    } else {
      try {
        // If it's an object, create a new instance of the object (it should
        // be a bean, or there will be trouble)
        Object newOb = type.newInstance();

        // Copy the XML element into the bean
        readObject(newOb, element);

        return newOb;
      } catch (InstantiationException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      } catch (IllegalAccessException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      }
    }
  }
Beispiel #13
0
 public static ScoreMenu queryFromFile(Class classes, Course courses) {
   MainWindow.initDataFile(SCORE_MENU_FILE);
   DataInputStream input;
   Class tempClass = new Class();
   Student student;
   Course course = new Course();
   int[] testTime = new int[5];
   int numberOfAttendTestStudent;
   long idOfStudents[];
   float scoreOfTest[];
   try {
     input = new DataInputStream(new FileInputStream(SCORE_MENU_FILE));
     while (input.available() > 0) {
       tempClass.setGrade(input.readInt());
       tempClass.setMajor(input.readUTF());
       tempClass.setClassNumber(input.readInt());
       int studentNumber = input.readInt();
       tempClass.setStudentNumber(0);
       for (int i = 0; i < studentNumber; i++) {
         student = new Student();
         student.setId(input.readLong());
         student.setName(input.readUTF());
         tempClass.addStudent(student);
       }
       course.setId(input.readUTF());
       course.setName(input.readUTF());
       course.setCredit(input.readFloat());
       course.setPeriod(input.readInt());
       for (int i = 0; i < 5; i++) testTime[i] = input.readInt();
       numberOfAttendTestStudent = input.readInt();
       idOfStudents = new long[numberOfAttendTestStudent];
       scoreOfTest = new float[numberOfAttendTestStudent];
       for (int i = 0; i < numberOfAttendTestStudent; i++) idOfStudents[i] = input.readLong();
       for (int i = 0; i < numberOfAttendTestStudent; i++) scoreOfTest[i] = input.readFloat();
       if ((classes.equals(tempClass)) && (courses.equals(course))) {
         input.close();
         return new ScoreMenu(
             tempClass, course, testTime, numberOfAttendTestStudent, idOfStudents, scoreOfTest);
       }
     }
     input.close();
     return null;
   } catch (Exception e) {
     return null;
   }
 }
Beispiel #14
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);
    }
  }
  @SuppressWarnings("rawtypes")
  private static void writeObjectToStream(Object obj, DataOutputStream data) throws IOException {
    Class objClass = obj.getClass();

    if (objClass.equals(Boolean.class)) {
      data.writeBoolean((Boolean) obj);
    } else if (objClass.equals(Byte.class)) {
      data.writeByte((Byte) obj);
    } else if (objClass.equals(Integer.class)) {
      data.writeInt((Integer) obj);
    } else if (objClass.equals(String.class)) {
      data.writeUTF((String) obj);
    } else if (objClass.equals(Double.class)) {
      data.writeDouble((Double) obj);
    } else if (objClass.equals(Float.class)) {
      data.writeFloat((Float) obj);
    } else if (objClass.equals(Long.class)) {
      data.writeLong((Long) obj);
    } else if (objClass.equals(Short.class)) {
      data.writeShort((Short) obj);
    }
  }
 /**
  * Exception processor for exceptions detected from the parser. (This is invoked by the parser
  * when an error is detected).
  *
  * @param sipMessage -- the message that incurred the error.
  * @param ex -- parse exception detected by the parser.
  * @param header -- header that caused the error.
  * @throws ParseException Thrown if we want to reject the message.
  */
 public void handleException(
     ParseException ex, SIPMessage sipMessage, Class hdrClass, String header, String message)
     throws ParseException {
   if (LogWriter.needsLogging) stack.logWriter.logException(ex);
   // Log the bad message for later reference.
   if ((hdrClass != null)
       && (hdrClass.equals(From.class)
           || hdrClass.equals(To.class)
           || hdrClass.equals(CSeq.class)
           || hdrClass.equals(Via.class)
           || hdrClass.equals(CallID.class)
           || hdrClass.equals(RequestLine.class)
           || hdrClass.equals(StatusLine.class))) {
     stack.logBadMessage(message);
     throw ex;
   } else {
     sipMessage.addUnparsed(header);
   }
 }
  @SuppressWarnings("rawtypes")
  private static Object readObjectFromStream(DataInputStream data, Class curClass)
      throws IOException {
    if (curClass.equals(Boolean.class)) {
      return data.readBoolean();
    } else if (curClass.equals(Byte.class)) {
      return data.readByte();
    } else if (curClass.equals(Integer.class)) {
      return data.readInt();
    } else if (curClass.equals(String.class)) {
      return data.readUTF();
    } else if (curClass.equals(Double.class)) {
      return data.readDouble();
    } else if (curClass.equals(Float.class)) {
      return data.readFloat();
    } else if (curClass.equals(Long.class)) {
      return data.readLong();
    } else if (curClass.equals(Short.class)) {
      return data.readShort();
    }

    return null;
  }
Beispiel #18
0
  private static void writeValue(Object value, OutputStream os) throws IOException {

    if (value == null) {
      os.write(-1);
    } else {
      Class valueClass = value.getClass();
      // write 0 for a single value, 1 for array, and 2 for Vector
      if (valueClass.isArray()) {
        os.write(1);
        int length = Array.getLength(value);
        PDataStream.writeInt(length, os);
        Class componentType = valueClass.getComponentType();
        if (componentType.isPrimitive()) {
          // primitive
          PDataStream.writeBoolean(true, os);
          // 1: int;2: long; 3: byte; 4: boolean; 5: character; 6:
          // short; 7: float; 8: double
          writePrimitiveArray(componentType, value, length, os);
        } else {
          PDataStream.writeBoolean(false, os);
          PDataStream.writeUTF(componentType.getName(), os);
          Object[] oArr = (Object[]) value;
          for (int i = 0; i < length; i++) {
            writeValue(oArr[i], os);
          }
        }
      } else if (valueClass.equals(Vector.class)) {
        os.write(2);
        int size = ((Vector) value).size();
        PDataStream.writeInt(size, os);
        for (int i = 0; i < size; i++) {
          writeValue(((Vector) value).elementAt(i), os);
        }
      } else {
        os.write(0);
        writeRealObject(value, valueClass, os);
      }
    }
  }
Beispiel #19
0
 private static Class[] getValidBufferTypes(Class type) {
   if (type.equals(IntBuffer.class))
     return new Class[] {
       GLbitfield.class, GLenum.class, GLhandleARB.class, GLint.class, GLsizei.class, GLuint.class
     };
   else if (type.equals(FloatBuffer.class)) return new Class[] {GLclampf.class, GLfloat.class};
   else if (type.equals(ByteBuffer.class))
     return new Class[] {
       GLboolean.class, GLbyte.class, GLcharARB.class, GLchar.class, GLubyte.class, GLvoid.class
     };
   else if (type.equals(ShortBuffer.class))
     return new Class[] {GLhalf.class, GLshort.class, GLushort.class};
   else if (type.equals(DoubleBuffer.class)) return new Class[] {GLclampd.class, GLdouble.class};
   else if (type.equals(LongBuffer.class))
     return new Class[] {GLint64EXT.class, GLuint64EXT.class};
   else return new Class[] {};
 }
Beispiel #20
0
  /**
   * Reads an string into a basic type
   *
   * @param type The type of the string to read
   * @param str The string containing the value
   * @return The parsed value of the string
   */
  public static Object parseBasicType(Class type, String str) {
    // Parse the text based on the property type

    if (type.equals(Integer.TYPE) || Integer.class.isAssignableFrom(type)) {
      return new Integer(str);
    } else if (type.equals(Long.TYPE) || Long.class.isAssignableFrom(type)) {
      return new Long(str);
    } else if (type.equals(Short.TYPE) || Short.class.isAssignableFrom(type)) {
      return new Short(str);
    } else if (type.equals(Byte.TYPE) || Byte.class.isAssignableFrom(type)) {
      return new Byte(str);
    } else if (type.equals(Boolean.TYPE) || Boolean.class.isAssignableFrom(type)) {
      return new Boolean(str);
    } else if (type.equals(Float.TYPE) || Float.class.isAssignableFrom(type)) {
      return new Float(str);
    } else if (type.equals(Double.TYPE) || Double.class.isAssignableFrom(type)) {
      return new Double(str);
    }

    return null;
  }
 /*
  * (non-Javadoc)
  *
  * @see
  * org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer
  * #getAdapter(java.lang.Class)
  */
 public Object getAdapter(Class adapter) {
   if (adapter == null) return null;
   if (adapter.equals(IFileTransferPausable.class)) return null;
   return super.getAdapter(adapter);
 }
  private static boolean generateBufferParameterAddress(
      TypeMap type_map,
      PrintWriter writer,
      MethodDeclaration method,
      ParameterDeclaration param,
      Mode mode,
      boolean loopDeclared) {
    NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param);
    param.getType().accept(translator);
    writer.print("\t" + translator.getSignature() + param.getSimpleName());
    writer.print(BUFFER_ADDRESS_POSTFIX + " = ((");
    writer.print(translator.getSignature());
    Check check_annotation = param.getAnnotation(Check.class);
    writer.print(")");
    if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) {
      writer.print(
          "offsetToPointer("
              + param.getSimpleName()
              + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX
              + "))");
    } else {
      Class java_type = Utils.getJavaType(param.getType());
      if (Buffer.class.isAssignableFrom(java_type)
          || java_type.equals(CharSequence.class)
          || java_type.equals(CharSequence[].class)) {
        boolean explicitly_byte_sized =
            java_type.equals(Buffer.class)
                || translator.getAnnotationType().equals(type_map.getVoidType());
        if (explicitly_byte_sized) writer.print("(((char *)");
        if (method.getAnnotation(GenerateAutos.class) != null
            || (check_annotation != null && check_annotation.canBeNull())) {
          writer.print("safeGetBufferAddress(env, " + param.getSimpleName());
        } else {
          writer.print("(*env)->GetDirectBufferAddress(env, " + param.getSimpleName());
        }
        writer.print("))");
        writer.print(" + " + param.getSimpleName() + BUFFER_POSITION_POSTFIX);
        if (explicitly_byte_sized) writer.print("))");
      } else if (java_type.equals(String.class)) {
        writer.print("GetStringNativeChars(env, " + param.getSimpleName() + "))");
      } else throw new RuntimeException("Illegal type " + java_type);
    }
    writer.println(";");

    if (param.getAnnotation(StringList.class) != null) {
      if (Utils.getJavaType(param.getType()) != CharSequence[].class
          && (param.getAnnotation(GLchar.class) == null
              || param.getAnnotation(NullTerminated.class) == null
              || param.getAnnotation(NullTerminated.class).value().length() == 0))
        throw new RuntimeException(
            "StringList annotation can only be applied on null-terminated GLchar buffers.");

      if ("_str".equals(param.getSimpleName()))
        throw new RuntimeException(
            "The name '_str' is not valid for arguments annotated with StringList");

      // Declare loop counters and allocate string array
      if (!loopDeclared) {
        writer.println("\tunsigned int _str_i;");
        writer.println("\tGLchar *_str_address;");
        loopDeclared = true;
      }
      writer.println(
          "\tGLchar **"
              + param.getSimpleName()
              + STRING_LIST_POSTFIX
              + " = (GLchar **) malloc("
              + param.getAnnotation(StringList.class).value()
              + "*sizeof(GLchar*));");
    }
    return loopDeclared;
  }
 public boolean canConvert(Class type) {
   return type.equals(Date.class);
 }
Beispiel #24
0
 public String translateAnnotation(Class annotation_type) {
   if (annotation_type.equals(GLuint.class)) return "i";
   else if (annotation_type.equals(GLint.class)) return "i";
   else if (annotation_type.equals(GLushort.class)) return "s";
   else if (annotation_type.equals(GLshort.class)) return "s";
   else if (annotation_type.equals(GLubyte.class)) return "b";
   else if (annotation_type.equals(GLbyte.class)) return "b";
   else if (annotation_type.equals(GLfloat.class)) return "f";
   else if (annotation_type.equals(GLdouble.class)) return "d";
   else if (annotation_type.equals(GLhalf.class)) return "h";
   else if (annotation_type.equals(GLuint64EXT.class)) return "i64";
   else if (annotation_type.equals(GLint64EXT.class)) return "i64";
   else if (annotation_type.equals(GLboolean.class) || annotation_type.equals(GLvoid.class))
     return "";
   else throw new RuntimeException(annotation_type + " is not allowed");
 }
  private void loadPluginsIntoClassLoader() {
    File pluginsFile = environment.pluginsFile();
    if (!pluginsFile.exists()) {
      return;
    }
    if (!pluginsFile.isDirectory()) {
      return;
    }

    ClassLoader classLoader = settings.getClassLoader();
    Class classLoaderClass = classLoader.getClass();
    Method addURL = null;
    while (!classLoaderClass.equals(Object.class)) {
      try {
        addURL = classLoaderClass.getDeclaredMethod("addURL", URL.class);
        addURL.setAccessible(true);
        break;
      } catch (NoSuchMethodException e) {
        // no method, try the parent
        classLoaderClass = classLoaderClass.getSuperclass();
      }
    }
    if (addURL == null) {
      logger.debug(
          "Failed to find addURL method on classLoader [" + classLoader + "] to add methods");
      return;
    }

    File[] pluginsFiles = pluginsFile.listFiles();
    for (File pluginFile : pluginsFiles) {
      if (!pluginFile.getName().endsWith(".zip")) {
        continue;
      }
      if (logger.isTraceEnabled()) {
        logger.trace("Processing [{}]", pluginFile);
      }

      String pluginNameNoExtension =
          pluginFile.getName().substring(0, pluginFile.getName().lastIndexOf('.'));
      File extractedPluginDir =
          new File(new File(environment.workFile(), "plugins"), pluginNameNoExtension);
      extractedPluginDir.mkdirs();

      File stampsDir = new File(new File(environment.workFile(), "plugins"), "_stamps");
      stampsDir.mkdirs();

      boolean extractPlugin = true;
      File stampFile = new File(stampsDir, pluginNameNoExtension + ".stamp");
      if (stampFile.exists()) {
        // read it, and check if its the same size as the pluginFile
        RandomAccessFile raf = null;
        try {
          raf = new RandomAccessFile(stampFile, "r");
          long size = raf.readLong();
          if (size == pluginFile.length()) {
            extractPlugin = false;
            if (logger.isTraceEnabled()) {
              logger.trace("--- No need to extract plugin, same size [" + size + "]");
            }
          }
        } catch (Exception e) {
          // ignore and extract the plugin
        } finally {
          if (raf != null) {
            try {
              raf.close();
            } catch (IOException e) {
              // ignore
            }
          }
        }
      }

      if (extractPlugin) {
        if (logger.isTraceEnabled()) {
          logger.trace("--- Extracting plugin to [" + extractedPluginDir + "]");
        }
        deleteRecursively(extractedPluginDir, false);

        ZipFile zipFile = null;
        try {
          zipFile = new ZipFile(pluginFile);
          Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
          while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = zipEntries.nextElement();
            if (!(zipEntry.getName().endsWith(".jar") || zipEntry.getName().endsWith(".zip"))) {
              continue;
            }
            String name = zipEntry.getName().replace('\\', '/');
            File target = new File(extractedPluginDir, name);
            Streams.copy(zipFile.getInputStream(zipEntry), new FileOutputStream(target));
          }
        } catch (Exception e) {
          logger.warn("Failed to extract plugin [" + pluginFile + "], ignoring...", e);
          continue;
        } finally {
          if (zipFile != null) {
            try {
              zipFile.close();
            } catch (IOException e) {
              // ignore
            }
          }
        }

        try {
          RandomAccessFile raf = new RandomAccessFile(stampFile, "rw");
          raf.writeLong(pluginFile.length());
          raf.close();
        } catch (Exception e) {
          // ignore
        }
      }

      try {
        for (File jarToAdd : extractedPluginDir.listFiles()) {
          if (!(jarToAdd.getName().endsWith(".jar") || jarToAdd.getName().endsWith(".zip"))) {
            continue;
          }
          addURL.invoke(classLoader, jarToAdd.toURI().toURL());
        }
      } catch (Exception e) {
        logger.warn("Failed to add plugin [" + pluginFile + "]", e);
      }
    }
  }