private void generateView(
      Map<String, DesignDocument.View> views, Method me, Class<?> handledType) {
    String name = me.getName();
    if (!name.startsWith("findBy") && !name.equals("getAll")) {
      throw new ViewGenerationException(
          String.format(
              "The method: %s in %s annotated with GenerateView does not conform to the naming convention of 'findByXxxx'",
              name, me.getDeclaringClass()));
    }

    Class<?> type = resolveReturnType(me);
    if (type == null) {
      if (handledType != null) {
        type = handledType;
      } else {
        throw new ViewGenerationException(
            "Could not resolve return type for method: %s in %s",
            me.getName(), me.getDeclaringClass());
      }
    }

    String typeDiscriminator = resolveTypeDiscriminator(type);

    if (name.equals("getAll")) {
      if (typeDiscriminator.length() < 1) {
        throw new ViewGenerationException(
            String.format(
                "Cannot generate 'all' view for %s. No type discriminator could be resolved. Try annotate unique field(s) with @TypeDiscriminator",
                type.getDeclaringClass()));
      }
      views.put("all", generateAllView(typeDiscriminator));
      return;
    }

    String finderName = name.substring(6);
    String fieldName = resolveFieldName(me, finderName);
    Method getter = findMethod(type, "get" + fieldName);
    if (getter == null) {
      // try pluralis
      fieldName += "s";
      getter = findMethod(type, "get" + fieldName);
    }
    if (getter == null) {
      throw new ViewGenerationException(
          "Could not generate view for method %s. No get method found for property %s in %s",
          name, name.substring(6), type);
    }

    fieldName = firstCharToLowerCase(fieldName);

    DesignDocument.View view;
    if (isIterable(getter.getReturnType())) {
      view = generateFindByIterableView(fieldName, typeDiscriminator);
    } else {
      view = generateFindByView(fieldName, typeDiscriminator);
    }

    views.put("by_" + firstCharToLowerCase(finderName), view);
  }
  /**
   * Handles a received {@link MBeanServerConnection} invocation
   *
   * @param channel The channel the request was received on
   * @param remoteAddress The remote address of the caller
   * @param buffer THe buffer received
   */
  public static void handleJMXRequest(
      Channel channel, SocketAddress remoteAddress, ChannelBuffer buffer) {
    buffer.resetReaderIndex();
    /* The request write */
    //		cb.writeByte(OpCode.JMX_REQUEST.op());  // 1
    //		cb.writeBytes(domainInfoData);   // domain data
    //		cb.writeInt(reqId);					// 4
    //		cb.writeByte(methodToKey.get(method)); // 1
    //		cb.writeInt(sargs.length);  			// 4
    //		cb.writeBytes(sargs);		           // sargs.length
    Object result = null;
    MBeanServerConnection server = null;
    buffer.skipBytes(1);
    byte domainIndicator = buffer.readByte();
    if (domainIndicator == 0) {
      server = JMXHelper.getHeliosMBeanServer();
    } else {
      byte[] domainBytes = new byte[domainIndicator];
      buffer.readBytes(domainBytes);
      String domain = new String(domainBytes);
      server = JMXHelper.getLocalMBeanServer(true, domain);
      if (server == null) {
        result = new SmallException("Failed to locate MBeanServer for domain [" + domain + "]");
      }
    }
    int reqId = buffer.readInt();
    byte methodId = buffer.readByte();
    if (result == null) {
      int payloadSize = buffer.readInt();
      byte[] payload = new byte[payloadSize];
      buffer.readBytes(payload);
      Object[] params = getInput(payload);
      Method targetMethod = null;
      try {
        targetMethod = keyToMethod.get(methodId);
        if (targetMethod == null) {
          result =
              new SmallException(
                  "Failed to handle MBeanServerConnection invocation because method Op Code ["
                      + methodId
                      + "] was not recognized");
        } else {
          if ("addNotificationListener".equals(targetMethod.getName())
              && !targetMethod.getParameterTypes()[1].equals(ObjectName.class)) {

          } else if ("removeNotificationListener".equals(targetMethod.getName())
              && !targetMethod.getParameterTypes()[1].equals(ObjectName.class)) {

          } else {
            result = targetMethod.invoke(server, params);
          }
        }
      } catch (Throwable t) {
        SimpleLogger.warn("Failed to invoke [", targetMethod, "]", t);
        result = new SmallException(t.toString());
      }
    }
    writeJMXResponse(reqId, methodId, channel, remoteAddress, result);
  }
Beispiel #3
0
 public void process(File cFile) {
   try {
     String cName = ClassNameFinder.thisClass(BinaryFile.read(cFile));
     if (!cName.contains("")) return; // Ignore unpackaged classes
     testClass = Class.forName(cName);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   TestMethods testMethods = new TestMethods();
   Method creator = null;
   Method cleanup = null;
   for (Method m : testClass.getDeclaredMethods()) {
     testMethods.addIfTestMethod(m);
     if (creator == null) creator = checkForCreatorMethod(m);
     if (cleanup == null) cleanup = checkForCleanupMethod(m);
   }
   if (testMethods.size() > 0) {
     if (creator == null)
       try {
         if (!Modifier.isPublic(testClass.getDeclaredConstructor().getModifiers())) {
           Print.print("Error: " + testClass + " default constructor must be public");
           System.exit(1);
         }
       } catch (NoSuchMethodException e) {
         // Synthesized default constructor; OK
       }
     Print.print(testClass.getName());
   }
   for (Method m : testMethods) {
     Print.printnb("  . " + m.getName() + " ");
     try {
       Object testObject = createTestObject(creator);
       boolean success = false;
       try {
         if (m.getReturnType().equals(boolean.class)) success = (Boolean) m.invoke(testObject);
         else {
           m.invoke(testObject);
           success = true; // If no assert fails
         }
       } catch (InvocationTargetException e) {
         // Actual exception is inside e:
         Print.print(e.getCause());
       }
       Print.print(success ? "" : "(failed)");
       testsRun++;
       if (!success) {
         failures++;
         failedTests.add(testClass.getName() + ": " + m.getName());
       }
       if (cleanup != null) cleanup.invoke(testObject, testObject);
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
 }
  /**
   * Computes the set of emit methods in the Assembler for a given IA32 opcode.
   *
   * @param emitters the set of all emit methods
   * @param opcode the opcode being examined
   */
  private static EmitterSet buildSetForOpcode(Method[] emitters, String opcode) {
    EmitterSet s = new EmitterSet();
    for (int i = 0; i < emitters.length; i++) {
      Method m = emitters[i];
      if (m.getName().startsWith("emit" + opcode + "_") || m.getName().equals("emit" + opcode)) {
        s.add(new EmitterDescriptor(m.getName(), m.getParameterTypes()));
      }
    }

    return s;
  }
 private static Method findMethod(ObjArray methods, Symbol name, Symbol signature) {
   int len = (int) methods.getLength();
   // methods are sorted, so do binary search
   int l = 0;
   int h = len - 1;
   while (l <= h) {
     int mid = (l + h) >> 1;
     Method m = (Method) methods.getObjAt(mid);
     int res = m.getName().fastCompare(name);
     if (res == 0) {
       // found matching name; do linear search to find matching signature
       // first, quick check for common case
       if (m.getSignature().equals(signature)) return m;
       // search downwards through overloaded methods
       int i;
       for (i = mid - 1; i >= l; i--) {
         Method m1 = (Method) methods.getObjAt(i);
         if (!m1.getName().equals(name)) break;
         if (m1.getSignature().equals(signature)) return m1;
       }
       // search upwards
       for (i = mid + 1; i <= h; i++) {
         Method m1 = (Method) methods.getObjAt(i);
         if (!m1.getName().equals(name)) break;
         if (m1.getSignature().equals(signature)) return m1;
       }
       // not found
       if (Assert.ASSERTS_ENABLED) {
         int index = linearSearch(methods, name, signature);
         if (index != -1) {
           throw new DebuggerException("binary search bug: should have found entry " + index);
         }
       }
       return null;
     } else if (res < 0) {
       l = mid + 1;
     } else {
       h = mid - 1;
     }
   }
   if (Assert.ASSERTS_ENABLED) {
     int index = linearSearch(methods, name, signature);
     if (index != -1) {
       throw new DebuggerException("binary search bug: should have found entry " + index);
     }
   }
   return null;
 }
    public ProxiedMethod(Method method) {
      this.method = method;
      this.name = // method instanceof Constructor ? "<init>" :
          method.getName();
      this.owner = method.getDeclaringClass();

      StringBuffer jni_sig = new StringBuffer("("), c_sig = new StringBuffer();

      retCapitalized = jni_capitalized(method.getReturnType());
      String[] sigArg = c_signature(method.getReturnType(), "?");
      c_sig.append(retType = sigArg[0]).append(" ").append(name).append("(");
      int i = 0;
      for (Class c : method.getParameterTypes()) {
        jni_sig.append(jni_signature(c));
        if (i > 0) c_sig.append(", ");

        String argName = "arg" + (i + 1);
        sigArg = c_signature(c, argName);
        String argType = sigArg[0];

        argTypes.add(argType);
        argNames.add(argName);
        argValues.add(sigArg[1]);

        c_sig.append(argType).append(" ").append(argName);
        i++;
      }
      c_sig.append(")");
      jni_sig.append(")").append(jni_signature(method.getReturnType()));
      this.jni_signature = jni_sig.toString();
      this.c_signature = c_sig.toString();
    }
  static {
    try {
      Map<String, Method> orderedMethods = new TreeMap<String, Method>();
      for (Method m : MBeanServerConnection.class.getDeclaredMethods()) {
        orderedMethods.put(m.toGenericString(), m);
      }
      Method[] methods = orderedMethods.values().toArray(new Method[orderedMethods.size()]);
      Map<String, Method> asynchMethods = new TreeMap<String, Method>();
      for (Method asynchMethod : AsynchJMXResponseListener.class.getDeclaredMethods()) {
        asynchMethods.put(asynchMethod.getName(), asynchMethod);
      }

      Map<Method, Byte> m2k = new HashMap<Method, Byte>(methods.length);
      Map<Byte, Method> k2m = new HashMap<Byte, Method>(methods.length);
      Map<Byte, Method> k2am = new HashMap<Byte, Method>(methods.length);
      for (int i = 0; i < methods.length; i++) {
        m2k.put(methods[i], (byte) i);
        k2m.put((byte) i, methods[i]);
        Method asynchMethod = asynchMethods.get(methods[i].getName() + "Response");
        if (asynchMethod == null)
          throw new RuntimeException(
              "Failed to find asynch handler for [" + methods[i].toGenericString() + "]",
              new Throwable());
        k2am.put((byte) i, asynchMethod);
      }
      methodToKey = Collections.unmodifiableMap(m2k);
      keyToMethod = Collections.unmodifiableMap(k2m);
      keyToAsynchMethod = Collections.unmodifiableMap(k2am);
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
  }
Beispiel #8
0
 public Object invoke(Object proxy, Method method, Object[] args) {
   if (method.getName().equals("windowEnteringFullScreen")) {
     cc.opts.fullScreen = true;
     cc.menu.fullScreen.setSelected(cc.opts.fullScreen);
     updateMacMenuFS();
     showToolbar(cc.showToolbar);
   } else if (method.getName().equals("windowExitingFullScreen")) {
     cc.opts.fullScreen = false;
     cc.menu.fullScreen.setSelected(cc.opts.fullScreen);
     updateMacMenuFS();
     showToolbar(cc.showToolbar);
   } else if (method.getName().equals("windowEnteredFullScreen")) {
     cc.sizeWindow();
   }
   return null;
 }
Beispiel #9
0
    protected void generateDelegateCode(
        Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {

      String mname = method.getName();
      if (jdbc4WrapperMethod(mname)) {
        generateWrapperDelegateCode(intfcl, genclass, method, iw);
        return;
      }

      Class retType = method.getReturnType();

      iw.println("if (proxyConn != null) proxyConn.maybeDirtyTransaction();");
      iw.println();

      if (mname.equals("close")) {
        iw.println("if (! this.isDetached())");
        iw.println("{");
        iw.upIndent();

        iw.println("if (creator instanceof Statement)");
        iw.upIndent();
        iw.println(
            "parentPooledConnection.markInactiveResultSetForStatement( (Statement) creator, inner );");
        iw.downIndent();
        iw.println("else if (creator instanceof DatabaseMetaData)");
        iw.upIndent();
        iw.println("parentPooledConnection.markInactiveMetaDataResultSet( inner );");
        iw.downIndent();
        iw.println("else if (creator instanceof Connection)");
        iw.upIndent();
        iw.println("parentPooledConnection.markInactiveRawConnectionResultSet( inner );");
        iw.downIndent();
        iw.println(
            "else throw new InternalError(\042Must be Statement or DatabaseMetaData -- Bad Creator: \042 + creator);");

        iw.println(
            "if (creatorProxy instanceof ProxyResultSetDetachable) ((ProxyResultSetDetachable) creatorProxy).detachProxyResultSet( this );");

        iw.println("this.detach();");
        iw.println("inner.close();");
        iw.println("this.inner = null;");

        iw.downIndent();
        iw.println("}");
      } else if (mname.equals("getStatement")) {
        iw.println("if (creator instanceof Statement)");
        iw.upIndent();
        iw.println("return (Statement) creatorProxy;");
        iw.downIndent();
        iw.println("else if (creator instanceof DatabaseMetaData)");
        iw.upIndent();
        iw.println("return null;");
        iw.downIndent();
        iw.println(
            "else throw new InternalError(\042Must be Statement or DatabaseMetaData -- Bad Creator: \042 + creator);");
      } else if (mname.equals("isClosed")) {
        iw.println("return this.isDetached();");
      } else super.generateDelegateCode(intfcl, genclass, method, iw);
    }
Beispiel #10
0
  static <T> T set(Class<T> interf, Object value) {
    Properties p = new Properties();
    Method ms[] = interf.getMethods();

    for (Method m : ms) {
      p.put(m.getName(), value);
    }
    return Configurable.createConfigurable(interf, (Map<Object, Object>) p);
  }
Beispiel #11
0
 public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
   Object obj = null;
   if (CLOSE_METHOD_NAME.equals(m.getName())) {
     SimpleConnectionPool.pushConnectionBackToPool(this);
   } else {
     obj = m.invoke(m_originConnection, args);
   }
   lastAccessTime = System.currentTimeMillis();
   return obj;
 }
 private static int linearSearch(ObjArray methods, Symbol name, Symbol signature) {
   int len = (int) methods.getLength();
   for (int index = 0; index < len; index++) {
     Method m = (Method) methods.getObjAt(index);
     if (m.getSignature().equals(signature) && m.getName().equals(name)) {
       return index;
     }
   }
   return -1;
 }
Beispiel #13
0
    protected void generatePostDelegateCode(
        Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {
      if ("setClientInfo".equals(method.getName())) {
        super.generatePostDelegateCode(intfcl, genclass, method, iw);

        iw.downIndent();
        iw.println("}");
        iw.println("catch (Exception e)");
        iw.println("{ throw SqlUtils.toSQLClientInfoException( e ); }");
      } else super.generatePostDelegateCode(intfcl, genclass, method, iw);
    }
Beispiel #14
0
    protected void generatePreDelegateCode(
        Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {
      if ("setClientInfo".equals(method.getName())) {
        iw.println("try");
        iw.println("{");
        iw.upIndent();

        super.generatePreDelegateCode(intfcl, genclass, method, iw);

      } else super.generatePreDelegateCode(intfcl, genclass, method, iw);
    }
  private Method findPublicVoidMethod(Class<?> aClass, String methodName) {
    for (Method method : aClass.getDeclaredMethods()) {
      if (isPublic(method.getModifiers())
          && method.getReturnType() == void.class
          && methodName.equals(method.getName())) {
        return method;
      }
    }

    return null;
  }
Beispiel #16
0
 private static void generateWrapperDelegateCode(
     Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {
   String mname = method.getName();
   if ("isWrapperFor".equals(mname)) {
     iw.println("return ( isWrapperForInner( a ) || isWrapperForThis( a ) );");
   } else if ("unwrap".equals(mname)) {
     iw.println("if (this.isWrapperForInner( a )) return inner.unwrap( a );");
     iw.println("if (this.isWrapperForThis( a )) return this;");
     iw.println(
         "else throw new SQLException( this + \042 is not a wrapper for or implementation of \042 + a.getName());");
   }
 }
    /**
     * This function returns the check_modified method from the class type provided.
     *
     * @param theClass the class in which to find the check_modified method
     * @return the check_modified method if it exists
     * @throws RuntimeException if check_modified does not exist.
     */
    private static Method getCheckModified(Class<? extends Invariant> theClass) {
      Method[] methods = theClass.getMethods();

      Method currentMethod;
      for (int i = 0; i < methods.length; i++) {
        currentMethod = methods[i];
        if (currentMethod.getName().lastIndexOf("check_modified")
            != -1) { // Method should be called check_modified
          return currentMethod;
        }
      }
      throw new RuntimeException("Cannot find check_modified method");
    }
  private void importMethod(DbJVClass dbClaz, Method method) throws DbException {
    if (dbClaz == null) {
      return;
    }

    String methodName = method.getName();
    boolean isConstructor = "<init>".equals(methodName);
    boolean isInitBlock = "<clinit>".equals(methodName);
    DbOOAbstractMethod oper = null;

    if (isInitBlock) {
      new DbJVInitBlock(dbClaz);
    } else if (isConstructor) {
      DbJVConstructor constr = new DbJVConstructor(dbClaz);
      importExceptions(constr, method);
      oper = constr;
    } else {
      // create method and return type
      DbJVMethod meth = new DbJVMethod(dbClaz);
      Type type = method.getReturnType();
      meth.setReturnType(toAdt(type));
      meth.setTypeUse(toTypeUse(type));

      // set method modifiers
      meth.setAbstract(method.isAbstract());
      meth.setFinal(method.isFinal());
      meth.setNative(method.isNative());
      meth.setStatic(method.isStatic());
      meth.setStrictfp(method.isStrictfp());
      meth.setSynchronized(method.isSynchronized());
      // method.isTransient()
      // method.isVolatile()
      importExceptions(meth, method);

      oper = meth;
    }

    // set name and visibility
    if (oper != null) {
      oper.setName(methodName);
      oper.setVisibility(toVisibility(method));

      // create parameters
      Type[] args = method.getArgumentTypes();
      for (Type arg : args) {
        DbJVParameter param = new DbJVParameter(oper);
        param.setType(toAdt(arg));
        param.setTypeUse(toTypeUse(arg));
      } // end for
    } // end if
  } // end importMethod()
    /**
     * @return the method of invariant named by theClass that produces a String representation of
     *     the invariant.
     */
    private static Method getOutputProducer(Class<? extends Invariant> theClass) {
      Method[] methods = theClass.getMethods();

      Method currentMethod;
      for (int i = 0; i < methods.length; i++) {
        currentMethod = methods[i];

        // Method should be called format_using
        if (currentMethod.getName().lastIndexOf("format_using") != -1) {
          return currentMethod;
        }
      }
      throw new RuntimeException("Cannot find format_using method");
    }
  protected void generateView(
      Map<String, org.ektorp.support.DesignDocument.View> views, Method me) {
    DocumentReferences referenceMetaData = me.getAnnotation(DocumentReferences.class);
    if (referenceMetaData == null) {
      LOG.warn("No DocumentReferences annotation found in method: ", me.getName());
      return;
    }
    if (!me.getName().startsWith("get")) {
      throw new ViewGenerationException(
          String.format(
              "The method: %s in %s annotated with DocumentReferences does not conform to the naming convention of 'getXxxx'",
              me.getName(), me.getDeclaringClass()));
    }

    if (Set.class.isAssignableFrom(me.getReturnType())) {
      generateSetBasedDocRefView(views, me, referenceMetaData);
    } else {
      throw new ViewGenerationException(
          String.format(
              "The return type of: %s in %s annotated with DocumentReferences is not supported. (Must be assignable from java.util.Set)",
              me.getName(), me.getDeclaringClass()));
    }
  }
Beispiel #21
0
 static Method findSingleMethod(Method[] methods, String name) {
   Method found = null;
   for (int i = 0, N = methods.length; i != N; ++i) {
     Method method = methods[i];
     if ((method != null) && name.equals(method.getName())) {
       if (found != null) {
         throw Context.reportRuntimeError2(
             "msg.no.overload", name, method.getDeclaringClass().getName());
       }
       found = method;
     }
   }
   return found;
 }
Beispiel #22
0
    protected void generateDelegateCode(
        Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {
      String mname = method.getName();
      if (jdbc4WrapperMethod(mname)) {
        generateWrapperDelegateCode(intfcl, genclass, method, iw);
        return;
      }

      Class retType = method.getReturnType();

      if (ResultSet.class.isAssignableFrom(retType)) {
        iw.println("ResultSet innerResultSet = inner." + CodegenUtils.methodCall(method) + ";");
        iw.println("if (innerResultSet == null) return null;");
        iw.println(
            "return new NewProxyResultSet( innerResultSet, parentPooledConnection, inner, this );");
      } else if (mname.equals("getConnection")) {
        iw.println("return this.proxyCon;");
      } else super.generateDelegateCode(intfcl, genclass, method, iw);
    }
  /**
   * Enumerate the methods of the Clob interface and get the list of methods present in the
   * interface
   *
   * @param LOB an instance of the Clob interface implementation
   */
  void buildMethodList(Object LOB) throws IllegalAccessException, InvocationTargetException {
    // If the given method throws the correct exception
    // set this to true and add it to the
    boolean valid = true;

    // create a list of the methods that fail the test
    Vector<Method> methodList = new Vector<Method>();

    // The class whose methods are to be verified
    Class clazz = Clob.class;

    // The list of the methods in the class that need to be invoked
    // and verified
    Method[] methods = clazz.getMethods();

    // Check each of the methods to ensure that
    // they throw the required exception
    for (int i = 0; i < methods.length; i++) {
      if (!checkIfExempted(methods[i])) {
        valid = checkIfMethodThrowsSQLException(LOB, methods[i]);

        // add the method to the list if the method does
        // not throw the required exception
        if (valid == false) methodList.add(methods[i]);

        // reset valid
        valid = true;
      }
    }

    if (!methodList.isEmpty()) {
      int c = 0;
      String failureMessage = "The Following methods don't throw " + "required exception - ";
      for (Method m : methodList) {
        c = c + 1;
        if (c == methodList.size() && c != 1) failureMessage += " & ";
        else if (c != 1) failureMessage += " , ";
        failureMessage += m.getName();
      }
      fail(failureMessage);
    }
  }
 /**
  * Quickie init test of the static initializer and print out of asynch response mappings
  *
  * @param args none
  */
 public static void main(String[] args) {
   SimpleLogger.info("Initialized");
   for (Map.Entry<Byte, Method> entry : keyToMethod.entrySet()) {
     Method am = keyToAsynchMethod.get(entry.getKey());
     SimpleLogger.info("\t", entry.getValue().getName(), " --> ", am.getName());
   }
   StringBuilder b = new StringBuilder("Mappings");
   for (Map.Entry<Byte, Method> entry : keyToMethod.entrySet()) {
     b.append("\n\t[")
         .append(entry.getKey())
         .append("]")
         .append("   --")
         .append(entry.getValue().getName())
         .append("--   ")
         .append("[")
         .append(methodToKey.get(entry.getValue()))
         .append("]");
   }
   SimpleLogger.info(b);
 }
Beispiel #25
0
    void generateFindMethodAndArgs(Method method, IndentedWriter iw) throws IOException {
      iw.println("Class[] argTypes = ");
      iw.println("{");
      iw.upIndent();

      Class[] argTypes = method.getParameterTypes();
      for (int i = 0, len = argTypes.length; i < len; ++i) {
        if (i != 0) iw.println(",");
        iw.print(CodegenUtils.simpleClassName(argTypes[i]) + ".class");
      }
      iw.println();
      iw.downIndent();
      iw.println("};");
      iw.println(
          "Method method = Connection.class.getMethod( \042"
              + method.getName()
              + "\042 , argTypes );");
      iw.println();
      iw.println("Object[] args = ");
      iw.println("{");
      iw.upIndent();

      for (int i = 0, len = argTypes.length; i < len; ++i) {
        if (i != 0) iw.println(",");
        String argName = CodegenUtils.generatedArgumentName(i);
        Class argType = argTypes[i];
        if (argType.isPrimitive()) {
          if (argType == boolean.class) iw.print("Boolean.valueOf( " + argName + " )");
          else if (argType == byte.class) iw.print("new Byte( " + argName + " )");
          else if (argType == char.class) iw.print("new Character( " + argName + " )");
          else if (argType == short.class) iw.print("new Short( " + argName + " )");
          else if (argType == int.class) iw.print("new Integer( " + argName + " )");
          else if (argType == long.class) iw.print("new Long( " + argName + " )");
          else if (argType == float.class) iw.print("new Float( " + argName + " )");
          else if (argType == double.class) iw.print("new Double( " + argName + " )");
        } else iw.print(argName);
      }

      iw.downIndent();
      iw.println("};");
    }
Beispiel #26
0
  public boolean handleCommand(String line, PrintWriter out) {
    String[] split = line.split("[\t ]");
    String commandName = split[0];

    try {
      Method[] methods = exportedInterface.getMethods();
      for (Method method : methods) {
        if (method.getName().equals(commandName) && method.getReturnType() == void.class) {
          return invokeMethod(line, out, method, split);
        }
      }
      throw new NoSuchMethodException();
    } catch (NoSuchMethodException nsmex) {
      out.println(fullName + ": didn't understand request \"" + line + "\".");
    } catch (Exception ex) {
      Log.warn(fullName + ": exception thrown while handling command \"" + line + "\".", ex);
      out.println(fullName + ": request denied \"" + line + "\" (" + ex.toString() + ").");
    } finally {
      out.flush();
      out.close();
    }
    return false;
  }
Beispiel #27
0
 /** Reflect operations demo */
 public static void reflect(Object obj) {
   // `cls用于描述对象所属的类`
   Class cls = obj.getClass();
   print("Class Name: " + cls.getCanonicalName());
   // `fields包含对象的所有属性`
   Field[] fields = cls.getDeclaredFields();
   print("List of fields:");
   for (Field f : fields) {
     print(String.format("%30s %15s", f.getType(), f.getName()));
   }
   // `methods包含对象的所有方法`
   Method[] methods = cls.getDeclaredMethods();
   print("List of methods:");
   for (Method m : methods)
     print(
         String.format(
             "%30s %15s %30s",
             m.getReturnType(), m.getName(), Arrays.toString(m.getParameterTypes())));
   Constructor[] constructors = cls.getConstructors();
   print("List of contructors:");
   for (Constructor c : constructors)
     print(String.format("%30s %15s", c.getName(), Arrays.toString(c.getParameterTypes())));
 }
Beispiel #28
0
  /* Print the current type graph to the dotfile */
  public void printDot(String title, Call call) {
    boolean printUnifications = false;
    PrintStream ps = PointsToAnalysis.v().file;
    if (ps == null) return;

    ps.println("\ndigraph F {");
    ps.println("   size = \"7,7\"; rankdir = LR;");
    ps.println("   orientation = landscape;");

    ps.println("   subgraph cluster1 {");
    ps.println("   \"Method: " + method.getName() + "\" [color=white];");

    if (nodes.isEmpty()) {
      ps.println("   \"empty graph\" [color = white];");
      ps.println("   }");
      ps.println("}");
      return;
    }

    for (Node node : nodes) {
      if (!printUnifications && !node.isRep()) continue;
      String color = "style=filled,fillcolor=";
      if (node.isheap && node.hasallocs) color += "red,";
      else if (node.isheap) color += "orange,";
      else if (node.hasallocs) color += "grey,";
      else color += "white,";
      // if (node.istouched) color = "khaki";
      // if (node.hassync) color = "khaki";
      String shape = "shape=";
      if (node.istouched) shape += "box";
      else shape += "ellipse";

      ps.println("   o" + node.id + "[label = \"" + node.getName() + "\"," + color + shape + "];");
    }
    ps.println("   }");

    Map<Integer, Map<Integer, String>> labels = new HashMap<Integer, Map<Integer, String>>();
    for (Field f : fedges.keySet())
      for (FieldEdge e : fedges.get(f)) {
        if (labels.containsKey(e.src.id)) {
          if (labels.get(e.src.id).containsKey(e.dst.id)) {
            labels.get(e.src.id).put(e.dst.id, "*");
            //                            labels.get(e.src.id).get(e.dst.id) + ", " +
            //                            e.field.getName());
          } else labels.get(e.src.id).put(e.dst.id, e.field.getName());

        } else {
          Map<Integer, String> is = new HashMap<Integer, String>();
          is.put(e.dst.id, e.field.getName());
          labels.put(e.src.id, is);
        }
      }
    for (Integer i : labels.keySet())
      for (Integer j : labels.get(i).keySet())
        ps.print(
            "   o"
                + i
                + " -> o"
                + j
                + "[label=\""
                + labels.get(i).get(j)
                + "\",style=solid,color=black];");

    for (Call ce : cedges.keySet())
      for (CallEdge e : cedges.get(ce)) {
        if (!(e.call instanceof VirtualCallExpr)) continue;
        // if (!e.call.equals(call)) continue;
        ps.print(
            "   o"
                + e.src.id
                + " -> o"
                + e.dst.id
                + "[label=\""
                + e.call
                + "\",style=solid,color=red];");
      }

    if (printUnifications)
      for (Node node : nodes)
        if (node.parent != null)
          ps.println("   o" + node.id + " -> o" + node.parent.id + " [color = blue];");

    ps.println("}");
  }
Beispiel #29
0
  /**
   * Given class of the interface for a fluid engine, build a concrete instance of that interface
   * that calls back into a Basic Engine for all methods in the interface.
   */
  private static BasicEngine buildCallbackEngine(String engineInterface, Class cEngine) {
    // build up list of callbacks for <engineInterface>
    StringBuffer decls = new StringBuffer();
    Method[] engineMethods = cEngine.getMethods();
    for (int i = 0; i < engineMethods.length; i++) {
      Method meth = engineMethods[i];
      // skip methods that aren't declared in the interface
      if (meth.getDeclaringClass() != cEngine) {
        continue;
      }
      decls.append(
          "    public " + Utils.asTypeDecl(meth.getReturnType()) + " " + meth.getName() + "(");
      Class[] params = meth.getParameterTypes();
      for (int j = 0; j < params.length; j++) {
        decls.append(Utils.asTypeDecl(params[j]) + " p" + j);
        if (j != params.length - 1) {
          decls.append(", ");
        }
      }
      decls.append(") {\n");
      decls.append(
          "        return ("
              + Utils.asTypeDecl(meth.getReturnType())
              + ")super.callNative(\""
              + meth.getName()
              + "\", new Object[] {");
      for (int j = 0; j < params.length; j++) {
        decls.append("p" + j);
        if (j != params.length - 1) {
          decls.append(", ");
        }
      }
      decls.append("} );\n");
      decls.append("    }\n\n");
    }

    // write template file
    String engineName = "BasicEngine_" + engineInterface;
    String fileName = engineName + ".java";
    try {
      String contents = Utils.readFile("lava/engine/basic/BasicEngineTemplate.java").toString();
      // remove package name
      contents = Utils.replaceAll(contents, "package lava.engine.basic;", "");
      // for class decl
      contents =
          Utils.replaceAll(
              contents, "extends BasicEngine", "extends BasicEngine implements " + engineInterface);
      // for constructor
      contents = Utils.replaceAll(contents, "BasicEngineTemplate", engineName);
      // for methods
      contents = Utils.replaceAll(contents, "// INSERT METHODS HERE", decls.toString());
      Utils.writeFile(fileName, contents);
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(1);
    }

    // compile the file
    try {
      Process jProcess = Runtime.getRuntime().exec("jikes " + fileName, null, null);
      jProcess.waitFor();
    } catch (Exception e) {
      System.err.println("Error compiling auto-generated file " + fileName);
      e.printStackTrace();
      System.exit(1);
    }

    // instantiate the class
    BasicEngine result = null;
    try {
      result = (BasicEngine) Class.forName(engineName).newInstance();
      // cleanup the files we made
      new File(engineName + ".java").delete();
      new File(engineName + ".class").delete();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }

    return result;
  }
Beispiel #30
0
  void generateTryCloserAndCatch(Class intfcl, String genclass, Method method, IndentedWriter iw)
      throws IOException {
    iw.downIndent();
    iw.println("}");
    iw.println("catch (NullPointerException exc)");
    iw.println("{");
    iw.upIndent();
    iw.println("if ( this.isDetached() )");
    iw.println("{");
    iw.upIndent();
    // iw.println( "System.err.print(\042probably 'cuz we're closed -- \042);" );
    // iw.println( "exc.printStackTrace();" );
    if ("close".equals(method.getName())) {
      iw.println("if (Debug.DEBUG && logger.isLoggable( MLevel.FINE ))");
      iw.println("{");
      iw.upIndent();
      iw.println("logger.log( MLevel.FINE, this + \042: close() called more than once.\042 );");

      // premature-detach-debug-debug only!
      if (PREMATURE_DETACH_DEBUG) {
        iw.println("prematureDetachRecorder.record();");
        iw.println(
            "logger.warning( prematureDetachRecorder.getDump(\042Apparent multiple close of "
                + getInnerTypeName()
                + ".\042) );");
      }
      // end-premature-detach-debug-only!

      iw.downIndent();
      iw.println("}");
    } else {
      // premature-detach-debug-debug only!
      if (PREMATURE_DETACH_DEBUG) {
        iw.println("prematureDetachRecorder.record();");
        iw.println(
            "logger.warning( prematureDetachRecorder.getDump(\042Use of already detached "
                + getInnerTypeName()
                + ".\042) );");
      }
      // end-premature-detach-debug-only!

      iw.println(
          "throw SqlUtils.toSQLException(\042You can't operate on a closed "
              + getInnerTypeName()
              + "!!!\042, exc);");
    }
    iw.downIndent();
    iw.println("}");
    iw.println("else throw exc;");
    iw.downIndent();
    iw.println("}");
    iw.println("catch (Exception exc)");
    iw.println("{");
    iw.upIndent();
    iw.println("if (! this.isDetached())");
    iw.println("{");
    iw.upIndent();
    // iw.println( "exc.printStackTrace();" );
    iw.println("throw parentPooledConnection.handleThrowable( exc );");
    iw.downIndent();
    iw.println("}");
    iw.println("else throw SqlUtils.toSQLException( exc );");
    iw.downIndent();
    iw.println("}");
  }