Пример #1
1
  protected PsmMethodAction(Class c, String m, Class[] argArray) {
    // This prevents IllegalAccessExceptions when attempting to
    // invoke methods on a class that is in another package and not
    // defined 'public'.
    if (!Modifier.isPublic(c.getModifiers())) {
      throw new IllegalPsmMethodActionException("Action class must be public.");
    }

    try {
      method = c.getMethod(m, argArray);
    } catch (NoSuchMethodException ex) {
      throw new IllegalPsmMethodActionException(ex.toString() + ": method " + m);
    }

    // Check each exception this method declares thrown.  If it declares
    // exceptions, and any of them are not runtime exceptions, abort.
    Class[] exceptionTypes = method.getExceptionTypes();
    for (int i = 0; i < exceptionTypes.length; i++) {
      Class exceptionClass = exceptionTypes[i];
      if (!RuntimeException.class.isAssignableFrom(exceptionClass)) {
        throw new IllegalPsmMethodActionException(
            "Method must not declare non-Runtime " + "exceptions.");
      }
    }

    // Ensure that the method returns PsmEvent
    if (PsmEvent.class != method.getReturnType()) {
      throw new IllegalPsmMethodActionException("Method return type must be PsmEvent");
    }

    // Ensure that both the method is both public and static.
    if (!Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers())) {
      throw new IllegalPsmMethodActionException("Method " + m + " must be static and public.");
    }
  }
Пример #2
0
  /** Performs peephole optimizations on a program's live methods. */
  private static void peephole(final BloatContext context) {

    final Set liveMethods = new TreeSet(new MemberRefComparator());
    final CallGraph cg = context.getCallGraph();
    liveMethods.addAll(cg.liveMethods());

    // Perform peephole optimizations. We do this separately because
    // some peephole optimizations do things to the stack that
    // inlining doesn't like. For instance, a peephole optimizations
    // might make it so that a method has a non-empty stack upon
    // return. Inlining will barf at the sight of this.
    BloatBenchmark.tr("Performing peephole optimizations");

    final Iterator iter = liveMethods.iterator();
    while (BloatBenchmark.PEEPHOLE && iter.hasNext()) {
      try {
        final MethodEditor live = context.editMethod((MemberRef) iter.next());
        Peephole.transform(live);
        context.commit(live.methodInfo());
        context.release(live.methodInfo());

      } catch (final NoSuchMethodException ex314) {
        BloatBenchmark.err.println("** Could not find method " + ex314.getMessage());
        ex314.printStackTrace(System.err);
        System.exit(1);
      }
    }
  }
Пример #3
0
 /**
  * Insert the source code details, if available.
  *
  * @param ped The given program element.
  */
 public void addSourcePosition(ProgramElementDoc ped, int indent) {
   if (!addSrcInfo) return;
   if (JDiff.javaVersion.startsWith("1.1")
       || JDiff.javaVersion.startsWith("1.2")
       || JDiff.javaVersion.startsWith("1.3")) {
     return; // position() only appeared in J2SE1.4
   }
   try {
     // Could cache the method for improved performance
     Class c = ProgramElementDoc.class;
     Method m = c.getMethod("position", null);
     Object sp = m.invoke(ped, null);
     if (sp != null) {
       for (int i = 0; i < indent; i++) outputFile.print(" ");
       outputFile.println("src=\"" + sp + "\"");
     }
   } catch (NoSuchMethodException e2) {
     System.err.println("Error: method \"position\" not found");
     e2.printStackTrace();
   } catch (IllegalAccessException e4) {
     System.err.println("Error: class not permitted to be instantiated");
     e4.printStackTrace();
   } catch (InvocationTargetException e5) {
     System.err.println("Error: method \"position\" could not be invoked");
     e5.printStackTrace();
   } catch (Exception e6) {
     System.err.println("Error: ");
     e6.printStackTrace();
   }
 }
  public Distribution<T> parse(String distrAsString) {
    DiscreteDistribution<T> dist = new DiscreteDistribution<T>();

    StringTokenizer tok = new StringTokenizer(distrAsString, ",");

    while (tok.hasMoreElements()) {
      String pair = tok.nextToken().trim();
      StringTokenizer sub = new StringTokenizer(pair, "/");

      try {
        T value = (T) domainType.getConstructor(String.class).newInstance(sub.nextToken().trim());
        Degree deg = (Degree) getDegreeStringConstructor().newInstance(sub.nextToken().trim());

        dist.put(value, deg);
      } catch (NoSuchMethodException nsme) {
        nsme.printStackTrace();
      } catch (IllegalAccessException iae) {
        iae.printStackTrace();
      } catch (InstantiationException ie) {
        ie.printStackTrace();
      } catch (InvocationTargetException ite) {
        ite.printStackTrace();
      }
    }
    return dist;
  }
Пример #5
0
 private static Object decode(Class returnType, String valueStr, TypeResolver resolver) {
   if (returnType.isArray()) {
     int sIndex = valueStr.indexOf("{");
     int eIndex = valueStr.lastIndexOf("}");
     String content = valueStr.substring(sIndex + 1, eIndex).trim();
     StringTokenizer tok = new StringTokenizer(content, ",");
     Object ar =
         java.lang.reflect.Array.newInstance(returnType.getComponentType(), tok.countTokens());
     int j = 0;
     while (tok.hasMoreElements()) {
       java.lang.reflect.Array.set(
           ar, j++, decode(returnType.getComponentType(), tok.nextToken(), resolver));
     }
     return ar;
   } else if (returnType.isEnum()) {
     try {
       String value = valueStr.trim();
       if (value.indexOf('.') > 0) {
         value = valueStr.substring(valueStr.lastIndexOf(".") + 1);
       }
       return returnType.getMethod("valueOf", String.class).invoke(null, value);
     } catch (IllegalAccessException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     } catch (InvocationTargetException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     } catch (NoSuchMethodException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     }
   } else if (String.class.equals(returnType)) {
     return unquote(valueStr);
   } else if (boolean.class.equals(returnType)) {
     return Boolean.valueOf(valueStr);
   } else if (int.class.equals(returnType)) {
     return Integer.valueOf(valueStr);
   } else if (double.class.equals(returnType)) {
     return Double.valueOf(valueStr);
   } else if (long.class.equals(returnType)) {
     return Long.valueOf(valueStr);
   } else if (float.class.equals(returnType)) {
     return Float.valueOf(valueStr);
   } else if (short.class.equals(returnType)) {
     return Short.valueOf(valueStr);
   } else if (char.class.equals(returnType)) {
     return unquote(valueStr).charAt(0);
   } else if (Class.class.equals(returnType)) {
     try {
       String cName = valueStr.trim().replace(".class", "");
       return resolver.resolveType(cName);
     } catch (ClassNotFoundException cnfe) {
       cnfe.printStackTrace();
       return Object.class;
     }
   }
   return null;
 }
Пример #6
0
  /**
   * forward an execute request to a helper instance associated with the rule
   *
   * @param recipient the recipient of the method from which execution of this rule was triggered or
   *     null if it was a static method
   * @param args the arguments of the method from which execution of this rule was triggered
   */
  private void execute(Object recipient, Object[] args) throws ExecuteException {
    // type check and createHelperAdapter the rule now if it has not already been done

    if (ensureTypeCheckedCompiled()) {

      // create a helper and get it to execute the rule
      // eventually we will create a subclass of helper for each rule and createHelperAdapter
      // an implementation of execute from the rule source. for now we create a generic
      // helper and call the generic execute method which interprets the rule
      HelperAdapter helper;
      try {
        Constructor constructor = helperImplementationClass.getConstructor(Rule.class);
        helper = (HelperAdapter) constructor.newInstance(this);
        // helper = (RuleHelper)helperClass.newInstance();
        // helper.setRule(this);
        helper.execute(recipient, args);
      } catch (NoSuchMethodException e) {
        // should not happen!!!
        System.out.println(
            "cannot find constructor "
                + helperImplementationClass.getCanonicalName()
                + "(Rule) for helper class");
        e.printStackTrace(System.out);
        return;
      } catch (InvocationTargetException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      } catch (InstantiationException e) {
        // should not happen
        System.out.println(
            "cannot create instance of " + helperImplementationClass.getCanonicalName());
        e.printStackTrace(System.out);
        return;
      } catch (IllegalAccessException e) {
        // should not happen
        System.out.println("cannot access " + helperImplementationClass.getCanonicalName());
        e.printStackTrace(System.out);
        return;
      } catch (ClassCastException e) {
        // should not happen
        System.out.println("cast exception " + helperImplementationClass.getCanonicalName());
        e.printStackTrace(System.out);
        return;
      } catch (EarlyReturnException e) {
        throw e;
      } catch (ThrowException e) {
        throw e;
      } catch (ExecuteException e) {
        System.out.println(getName() + " : " + e);
        throw e;
      } catch (Throwable throwable) {
        System.out.println(getName() + " : " + throwable);
        throw new ExecuteException(getName() + "  : caught " + throwable, throwable);
      }
    }
  }
  @Nullable
  static ClassLoader createPluginClassLoader(
      @NotNull File[] classPath,
      @NotNull ClassLoader[] parentLoaders,
      @NotNull IdeaPluginDescriptor pluginDescriptor) {

    if (pluginDescriptor.getUseIdeaClassLoader()) {
      try {
        final ClassLoader loader = PluginManagerCore.class.getClassLoader();
        final Method addUrlMethod = getAddUrlMethod(loader);

        for (File aClassPath : classPath) {
          final File file = aClassPath.getCanonicalFile();
          addUrlMethod.invoke(loader, file.toURI().toURL());
        }

        return loader;
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }

    PluginId pluginId = pluginDescriptor.getPluginId();
    File pluginRoot = pluginDescriptor.getPath();

    // if (classPath.length == 0) return null;
    if (isUnitTestMode()) return null;
    try {
      final List<URL> urls = new ArrayList<URL>(classPath.length);
      for (File aClassPath : classPath) {
        final File file =
            aClassPath
                .getCanonicalFile(); // it is critical not to have "." and ".." in classpath
                                     // elements
        urls.add(file.toURI().toURL());
      }
      return new PluginClassLoader(
          urls, parentLoaders, pluginId, pluginDescriptor.getVersion(), pluginRoot);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
Пример #8
0
  /**
   * Initializes the dispatcher servlet. This sets the post/get to true and calls the abstract setup
   * actions method.
   */
  @Override
  public void init() {
    setIsPostAllowed(true);
    setIsGetAllowed(true);

    try {
      setupActionMethods();
    } catch (NoSuchMethodException methodEx) {
      LogController.write(this, "FATAL: No such method: " + methodEx.getMessage());
      return;
    } finally {
      actionInitialized = true;
    }
  }
Пример #9
0
  /** Specializes the live methods in a program. */
  private static void specialize(final BloatContext context) {

    final CallGraph cg = context.getCallGraph();

    final Set liveMethods = new TreeSet(new MemberRefComparator());
    liveMethods.addAll(cg.liveMethods());

    // Specialize all possible methods
    final InlineStats stats = context.getInlineStats();

    if (BloatBenchmark.statsFile != null) {
      Specialize.STATS = true;
      stats.setConfigName("BloatBenchmark");
    }

    if (BloatBenchmark.MORPH != -1) {
      Specialize.MAX_MORPH = BloatBenchmark.MORPH;
    }
    final Specialize spec = new Specialize(context);

    if (Specialize.STATS) {
      stats.noteLiveMethods(liveMethods.size());
      stats.noteLiveClasses(cg.liveClasses().size());
    }

    BloatBenchmark.tr("Specializing live methods");
    final Iterator iter = liveMethods.iterator();

    for (int count = 0; iter.hasNext(); count++) {
      try {
        final MethodEditor live = context.editMethod((MemberRef) iter.next());

        if (context.ignoreMethod(live.memberRef())) {
          // Don't display ignored methods, it's misleading.
          continue;
        }

        BloatBenchmark.tr(
            "  " + count + ") " + live.declaringClass().name() + "." + live.name() + live.type());

        spec.specialize(live);

      } catch (final NoSuchMethodException ex2) {
        BloatBenchmark.err.println("** Could not find method " + ex2.getMessage());
        System.exit(1);
      }
    }
  }
Пример #10
0
 // convenience method for invoking a constructor;
 // used as a central point for exception handling for Java reflection
 // constructor calls
 private <T> T invokeConstructor(
     Class<T> clazz, Class<?>[] argumentClasses, Object[] argumentObjects) {
   try {
     Constructor<T> constructor = clazz.getConstructor(argumentClasses);
     return constructor.newInstance(argumentObjects);
   } catch (IllegalArgumentException e) {
     e.printStackTrace();
   } catch (InstantiationException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   } catch (InvocationTargetException e) {
     e.printStackTrace();
   } catch (SecurityException e) {
     e.printStackTrace();
   } catch (NoSuchMethodException e) {
     e.printStackTrace();
   }
   return null;
 }
Пример #11
0
  public Y call(X value) {
    Class cls = value.getClass();
    try {
      Method m = cls.getMethod(fieldName);
      return (Y) m.invoke(value);

    } catch (SecurityException e) {
      e.printStackTrace();
      throw new IllegalStateException();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
      throw new IllegalStateException();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
      throw new IllegalStateException();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
      throw new IllegalStateException();
    }
  }
Пример #12
0
 /**
  * Build the documentation, as specified by the given XML element.
  *
  * @param node the XML element that specifies which component to document.
  * @param contentTree content tree to which the documentation will be added
  */
 protected void build(XMLNode node, Content contentTree) {
   String component = node.name;
   try {
     invokeMethod(
         "build" + component,
         new Class<?>[] {XMLNode.class, Content.class},
         new Object[] {node, contentTree});
   } catch (NoSuchMethodException e) {
     e.printStackTrace();
     configuration.root.printError("Unknown element: " + component);
     throw new DocletAbortException(e);
   } catch (InvocationTargetException e) {
     throw new DocletAbortException(e.getCause());
   } catch (Exception e) {
     e.printStackTrace();
     configuration.root.printError(
         "Exception " + e.getClass().getName() + " thrown while processing element: " + component);
     throw new DocletAbortException(e);
   }
 }
Пример #13
0
  // convenience method for invoking a static method;
  // used as a central point for exception handling for Java reflection
  // static method calls
  private static Object invokeStaticMethod(Class<?> clazz, String methodName, Object... args) {
    // unfortunately Java does not seem to offer a way to call
    // a static method given a class object directly, so we have
    // to use reflection
    try {
      Method method = clazz.getMethod(methodName);
      return method.invoke(null, args);
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }

    return null;
  }
Пример #14
0
  /**
   * The main method.
   *
   * @param args the arguments
   */
  public static void main(String[] args) {
    Questionnaire quiz = new Questionnaire();
    try {
      quiz.initQuestionnaire("question_tolkien.txt");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    new QuestionnaireUI(quiz);
  }
Пример #15
0
  /** Inlines calls to static methods in the live methods of a given program. */
  private static void inline(final BloatContext context) {

    final Set liveMethods = new TreeSet(new MemberRefComparator());
    final CallGraph cg = context.getCallGraph();
    liveMethods.addAll(cg.liveMethods());

    BloatBenchmark.tr("Inlining " + liveMethods.size() + " live methods");

    if (BloatBenchmark.CALLEE_SIZE != -1) {
      Inline.CALLEE_SIZE = BloatBenchmark.CALLEE_SIZE;
    }

    final Iterator iter = liveMethods.iterator();
    for (int count = 0; BloatBenchmark.INLINE && iter.hasNext(); count++) {
      try {
        final MethodEditor live = context.editMethod((MemberRef) iter.next());

        if (context.ignoreMethod(live.memberRef())) {
          // Don't display ignored methods, it's misleading.
          continue;
        }

        BloatBenchmark.tr(
            "  " + count + ") " + live.declaringClass().name() + "." + live.name() + live.type());

        final Inline inline = new Inline(context, BloatBenchmark.SIZE);
        inline.setMaxCallDepth(BloatBenchmark.DEPTH);
        inline.inline(live);

        // Commit here in an attempt to conserve memory
        context.commit(live.methodInfo());
        context.release(live.methodInfo());

      } catch (final NoSuchMethodException ex3) {
        BloatBenchmark.err.println("** Could not find method " + ex3.getMessage());
        System.exit(1);
      }
    }
  }
Пример #16
0
 /**
  * Create a PropertyColumn from a property name, column name, row and column classes, and column
  * width. The render and editor default to null, and updateRow, updateSubsequentRows, and
  * updateTable all default to false.
  *
  * <p>This generates an editable column if a setter exists for this property, and a non-editable
  * property if the setter doesn't exist. For more complex behavior, override {@code
  * isEditable(_RowType)}
  *
  * @param pPropertyName The name of the property of instances of the specified row class
  * @param pColumnName The name of the column
  * @param pRowClass The class of the table row instances
  * @param pValueClass The class of the values of this column
  * @param pPrefWidth the preferred width of this column
  * @throws AssertionError if pRowClass doesn't have a getter for this property name.
  */
 public PropertyColumn(
     String pPropertyName,
     String pColumnName,
     Class pRowClass,
     Class pValueClass,
     int pPrefWidth) {
   super(pColumnName, getWrapper(pValueClass), pPrefWidth);
   try {
     mGetterMethod = generateGetter(pPropertyName, pRowClass, this);
   } catch (NoSuchMethodException e) {
     AssertionError err = new AssertionError(e.getMessage());
     err.initCause(e);
     throw err;
   }
   Method setter = null;
   try {
     setter = generateSetter(pPropertyName, pRowClass, this);
     setEditable(true);
   } catch (NoSuchMethodException nsme) {
     setEditable(false);
   }
   mSetterMethod = setter;
 }
Пример #17
0
 private Workbook handleExcel(List objs, Class clz, boolean isXssf, String message) {
   XSSFWorkbook wb = null;
   try {
     if (isXssf) {
       XSSFWorkbook w = new XSSFWorkbook();
     } else {
       HSSFWorkbook w = new HSSFWorkbook();
     }
     wb = new XSSFWorkbook();
     XSSFDataFormat format = wb.createDataFormat();
     XSSFSheet sheet = wb.createSheet(message + "备份记录"); // 取excel工作表对象
     XSSFCellStyle cellStyle = wb.createCellStyle(); // 设置excel单元格样式
     XSSFCellStyle passwordCellStyle = wb.createCellStyle(); // 设置密码单元格样式
     XSSFDataFormat passwordFormat = wb.createDataFormat();
     passwordCellStyle.setDataFormat(passwordFormat.getFormat(";;;"));
     List<ExcelHeader> headers = getHeaderList(clz);
     Collections.sort(headers);
     sheet.addMergedRegion(new CellRangeAddress(0, (short) 0, 0, (short) (headers.size() - 1)));
     Row r0 = sheet.createRow(0);
     Cell cell = r0.createCell(0);
     r0.setHeightInPoints(28);
     cell.setCellValue(message + "备份记录");
     Row r = sheet.createRow(1);
     r.setHeightInPoints(25);
     cell.setCellStyle(cellStyle);
     // 输出标题
     for (int i = 0; i < headers.size(); i++) {
       Cell cell1 = r.createCell(i);
       if (headers.get(i).getTitle().equals("密码")) cell1.setCellStyle(passwordCellStyle);
       else cell1.setCellStyle(cellStyle);
       cell1.setCellValue(headers.get(i).getTitle());
     }
     Object obj = null;
     // 输出用户资料信息
     if (message.indexOf("用户资料 ") > 0) {
       sheet.setColumnWidth(3, 32 * 150);
       sheet.setColumnWidth(4, 32 * 110);
       sheet.setColumnWidth(7, 32 * 120);
       for (int i = 0; i < objs.size(); i++) {
         r = sheet.createRow(i + 2);
         obj = objs.get(i);
         for (int j = 0; j < headers.size(); j++) {
           Cell cell2 = r.createCell(j);
           copyDefaultCellStyle(null, cell2, cellStyle, 0);
           if (getMethodName(headers.get(j)).equals("nabled"))
             cell2.setCellValue(BeanUtils.getProperty(obj, "enabled"));
           else if (getMethodName(headers.get(j)).equals("password")) {
             cell2.setCellStyle(passwordCellStyle);
             cell2.setCellValue(BeanUtils.getProperty(obj, getMethodName(headers.get(j))));
           } else cell2.setCellValue(BeanUtils.getProperty(obj, getMethodName(headers.get(j))));
         }
       }
     }
     // 输出房间使用信息数据
     else {
       sheet.setColumnWidth(0, 32 * 80);
       sheet.setColumnWidth(2, 32 * 100);
       sheet.setColumnWidth(3, 32 * 190);
       sheet.setColumnWidth(4, 32 * 190);
       sheet.setColumnWidth(5, 32 * 190);
       sheet.setColumnWidth(10, 32 * 130);
       for (int i = 0; i < objs.size(); i++) {
         r = sheet.createRow(i + 2);
         obj = objs.get(i);
         for (int j = 0; j < headers.size(); j++) {
           Cell cell2 = r.createCell(j);
           if (j == 3 || j == 4 || j == 5) {
             XSSFCellStyle cs3 = wb.createCellStyle();
             cell2.setCellValue(new Date());
             copyDefaultCellStyle(format, cell2, cs3, 1);
           }
           if (j == 10) {
             XSSFCellStyle cs2 = wb.createCellStyle();
             copyDefaultCellStyle(format, cell2, cs2, 2);
           }
           copyDefaultCellStyle(null, cell2, cellStyle, 0);
           cell2.setCellValue(BeanUtils.getProperty(obj, getMethodName(headers.get(j))));
         }
       }
     }
     // 设置行列的默认宽度和高度
   } catch (IllegalAccessException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (InvocationTargetException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (NoSuchMethodException e) {
     e.printStackTrace();
     logger.error(e);
   }
   return wb;
 }
Пример #18
0
  /**
   * Invokes the method specified by a method description.
   *
   * @param methodDescription the method description of the method that is to be invoked.
   */
  protected void invoke(MethodDescription methodDescription) throws InvocationTargetException {

    VParamUtil.throwIfNull(methodDescription);

    Object o = getObject(methodDescription.getObjectID());

    ObjectDescription oDesc = getObjectDescription(o);

    if (o == null) {
      throw new IllegalStateException("Object must not be null!");
    }

    if (methodDescription.getMethodType() == MethodType.REFERENCE) {

      Object[] parameters = methodDescription.getParameters();

      // error handling
      if (parameters.length > 1) {
        throw new IllegalArgumentException(
            "More than one parameter " + "for reference methods is not allowed!");
      }

      if (parameters.length > 0 && parameters[0] != null) {
        methodDescription.setReturnValue(parameters[0]);
      } else {
        methodDescription.setReturnValue(o);
      }

    } else if (o instanceof ProxyObject) {
      ProxyObject proxy = (ProxyObject) o;
      methodDescription.setReturnValue(proxy.invoke(methodDescription));
      if (!methodDescription
          .getReturnType()
          .equals(methodDescription.getReturnValue().getClass())) {
        System.err.println(">> ProxyObject: wrong type of return value!");
        generateErrorMessage(">> ProxyObject:" + " wrong type of return value!", methodDescription);
      }
    } else if (methodDescription.getMethodType() == MethodType.DEFAULT
        || methodDescription.getMethodType() == MethodType.CUSTOM_REFERENCE) {
      Method m = null;

      try {
        m =
            o.getClass()
                .getMethod(
                    methodDescription.getMethodName(), methodDescription.getParameterTypes());

        // access this method even if language visibility forbids
        // invocation of this method
        m.setAccessible(true);

        methodDescription.setReturnValue(m.invoke(o, methodDescription.getParameters()));

      } catch (NoSuchMethodException ex) {
        Logger.getLogger(ObjectInspector.class.getName()).log(Level.SEVERE, null, ex);
        generateErrorMessage(
            methodDescription.getMethodName() + "(): " + ex.toString(), methodDescription);
      } catch (IllegalAccessException ex) {
        Logger.getLogger(ObjectInspector.class.getName()).log(Level.SEVERE, null, ex);
        generateErrorMessage(
            methodDescription.getMethodName() + "(): " + ex.toString(), methodDescription);
      } catch (IllegalArgumentException ex) {
        System.err.println(">> ObjectInspector:" + " invoked method with wrong arguments!");

        String yourParamStr = "";
        String expectedParamStr = "";

        if (methodDescription.getParameters() != null) {

          for (int i = 0; i < methodDescription.getParameters().length; i++) {
            Object parameter = methodDescription.getParameters()[i];
            if (parameter != null) {
              yourParamStr += parameter.getClass().getName() + " ";
            } else {
              yourParamStr += "null ";
            }
          }
        } else {
          yourParamStr = "no parameters given!";
        }

        for (int i = 0; i < m.getParameterTypes().length; i++) {
          expectedParamStr += m.getParameterTypes()[i].getName() + " ";
        }

        System.err.println("   your parameters:     " + yourParamStr);
        System.err.println("   expected parameters: " + expectedParamStr);

        generateErrorMessage(
            methodDescription.getMethodName() + "(): method invoked with wrong arguments!",
            methodDescription);

      } catch (InvocationTargetException ex) {
        Logger.getLogger(ObjectInspector.class.getName()).log(Level.SEVERE, null, ex);
        generateErrorMessage(methodDescription, ex.getCause());
        throw ex;

      } catch (SecurityException ex) {
        Logger.getLogger(ObjectInspector.class.getName()).log(Level.SEVERE, null, ex);
        generateErrorMessage(
            methodDescription.getMethodName() + "(): " + ex.toString(), methodDescription);
      }
    } // end else if (o instanceof ProxyObject)
  }
Пример #19
0
    private int runEclipseCompiler(String[] output, List<String> cmdline) {
      try {
        List<String> final_cmdline = new LinkedList<String>(cmdline);

        // remove compiler name from argument list
        final_cmdline.remove(0);

        Class eclipseCompiler = Class.forName(ECLIPSE_COMPILER_CLASS);

        Method compileMethod = eclipseCompiler.getMethod("main", new Class[] {String[].class});

        final_cmdline.add(0, "-noExit");
        final_cmdline.add(0, "-progress");
        final_cmdline.add(0, "-verbose");

        File _logfile = new File(this.idata.getInstallPath(), "compile-" + getName() + ".log");

        if (Debug.isTRACE()) {
          final_cmdline.add(0, _logfile.getPath());
          final_cmdline.add(0, "-log");
        }

        // get log files / determine results...
        try {
          // capture stdout and stderr
          PrintStream _orgStdout = System.out;
          PrintStream _orgStderr = System.err;
          int error_count = 0;

          try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            EclipseStdOutHandler ownStdout = new EclipseStdOutHandler(outStream, this.listener);
            System.setOut(ownStdout);
            ByteArrayOutputStream errStream = new ByteArrayOutputStream();
            EclipseStdErrHandler ownStderr = new EclipseStdErrHandler(errStream, this.listener);
            System.setErr(ownStderr);

            compileMethod.invoke(
                null, new Object[] {final_cmdline.toArray(new String[final_cmdline.size()])});

            // TODO: launch thread which updates the progress
            output[0] = outStream.toString();
            output[1] = errStream.toString();
            error_count = ownStderr.getErrorCount();
            // for debugging: write output to log files
            if (error_count > 0 || Debug.isTRACE()) {
              File _out = new File(_logfile.getPath() + ".stdout");
              FileOutputStream _fout = new FileOutputStream(_out);
              _fout.write(outStream.toByteArray());
              _fout.close();
              _out = new File(_logfile.getPath() + ".stderr");
              _fout = new FileOutputStream(_out);
              _fout.write(errStream.toByteArray());
              _fout.close();
            }

          } finally {
            System.setOut(_orgStdout);
            System.setErr(_orgStderr);
          }

          if (error_count == 0) {
            return 0;
          }

          // TODO: construct human readable error message from log
          this.listener.emitNotification("Compiler reported " + error_count + " errors");

          return 1;
        } catch (FileNotFoundException fnfe) {
          this.listener.emitError("error compiling", fnfe.getMessage());
          return -1;
        } catch (IOException ioe) {
          this.listener.emitError("error compiling", ioe.getMessage());
          return -1;
        }

      } catch (ClassNotFoundException cnfe) {
        output[0] = "error getting eclipse compiler";
        output[1] = cnfe.getMessage();
        return -1;
      } catch (NoSuchMethodException nsme) {
        output[0] = "error getting eclipse compiler method";
        output[1] = nsme.getMessage();
        return -1;
      } catch (IllegalAccessException iae) {
        output[0] = "error calling eclipse compiler";
        output[1] = iae.getMessage();
        return -1;
      } catch (InvocationTargetException ite) {
        output[0] = "error calling eclipse compiler";
        output[1] = ite.getMessage();
        return -1;
      }
    }
Пример #20
0
  public static Map<String, String> toRequestMap(
      PaypalClassicModel paypalClassicModel, String format) {
    Map<String, String> returnMap = new HashMap<>();
    if (paypalClassicModel == null) {
      return returnMap;
    }
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    //        ValidatorFactory factory = Validation.byDefaultProvider()
    //                .configure()
    //                .messageInterpolator( new MyMessageInterpolator() )
    //                .buildValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<PaypalClassicModel>> violations =
        validator.validate(paypalClassicModel);
    if (violations.size() == 0) {
      try {
        for (Field field : FieldUtils.getAllFields(paypalClassicModel.getClass())) {
          if (field.getType().isAssignableFrom(String.class)) {
            if (BeanUtils.getProperty(paypalClassicModel, field.getName()) != null) {
              if (StringUtils.isNumeric(format)) {
                returnMap.put(
                    field.getName().toUpperCase() + format,
                    BeanUtils.getProperty(paypalClassicModel, field.getName()));
              } else {
                returnMap.put(
                    getFormatedKeyName(format, field.getName(), null),
                    BeanUtils.getProperty(paypalClassicModel, field.getName()));
              }
            }
          }
          if (PaypalClassicModel.class.isAssignableFrom(field.getType())) {

            if (PropertyUtils.getProperty(paypalClassicModel, field.getName()) != null) {
              returnMap.putAll(
                  toRequestMap(
                      (PaypalClassicModel)
                          PropertyUtils.getProperty(paypalClassicModel, field.getName()),
                      format));
            }
          }
          if (List.class.isAssignableFrom(field.getType())) {
            List listItem = (List) PropertyUtils.getProperty(paypalClassicModel, field.getName());
            if (listItem != null) {
              for (int i = 0; i < listItem.size(); i++) {
                if (listItem.get(i) instanceof PaypalClassicModel) {
                  PaypalCollection paypalCollection = field.getAnnotation(PaypalCollection.class);
                  if (paypalCollection != null
                      && StringUtils.isNotEmpty(paypalCollection.format())) {
                    String formatStr = field.getAnnotation(PaypalCollection.class).format();
                    returnMap.putAll(
                        toRequestMap(
                            (PaypalClassicModel) listItem.get(i),
                            getFormatedKeyName(formatStr, null, i)));
                  } else {
                    if (StringUtils.isNoneEmpty(format)) {
                      returnMap.putAll(
                          toRequestMap(
                              (PaypalClassicModel) listItem.get(i), format + String.valueOf(i)));
                    } else {
                      returnMap.putAll(
                          toRequestMap((PaypalClassicModel) listItem.get(i), String.valueOf(i)));
                    }
                  }
                }
                if (listItem.get(i) instanceof List) {
                  PaypalCollection paypalCollection = field.getAnnotation(PaypalCollection.class);
                  if (paypalCollection != null
                      && StringUtils.isNotEmpty(paypalCollection.format())) {
                    String formatStr = field.getAnnotation(PaypalCollection.class).format();
                    returnMap.putAll(
                        toRequestMap(
                            (List) listItem.get(i), getFormatedKeyName(formatStr, null, i)));
                  } else {
                    if (StringUtils.isNoneEmpty(format)) {
                      returnMap.putAll(
                          toRequestMap((List) listItem.get(i), format + String.valueOf(i)));
                    } else {
                      returnMap.putAll(toRequestMap((List) listItem.get(i), String.valueOf(i)));
                    }
                  }
                }
                if (listItem.get(i) instanceof String) {
                  PaypalCollection paypalCollection = field.getAnnotation(PaypalCollection.class);
                  if (paypalCollection != null
                      && StringUtils.isNotEmpty(paypalCollection.format())) {
                    String formatStr = paypalCollection.format();
                    formatStr = getFormatedKeyName(formatStr, field.getName(), i);
                    returnMap.put(
                        getFormatedKeyName(format, formatStr, null), listItem.get(i).toString());
                  } else {
                    returnMap.put(
                        getFormatedKeyName(format, field.getName(), null) + i,
                        listItem.get(i).toString());
                  }
                }
              }
            }
          }
        }
      } catch (IllegalAccessException e) {
        throw new ValidationException(e.getMessage());
      } catch (InvocationTargetException e) {
        throw new ValidationException(e.getMessage());
      } catch (NoSuchMethodException e) {
        throw new ValidationException(e.getMessage());
      }
    } else {
      StringBuffer buf = new StringBuffer();
      for (ConstraintViolation<PaypalClassicModel> violation : violations) {
        buf.append(violation.getMessage() + "\n");
      }
      throw new ValidationException(buf.toString());
    }
    return returnMap;
  }
Пример #21
0
  /**
   * Creates a new aspect container.
   *
   * @param aspectClass the aspect class
   */
  private static AspectContainer createAspectContainer(final Class aspectClass) {
    AspectDefinition aspectDefinition = null;

    Set definitions =
        SystemDefinitionContainer.getRegularAndVirtualDefinitionsFor(aspectClass.getClassLoader());
    for (Iterator iterator = definitions.iterator();
        iterator.hasNext() && aspectDefinition == null; ) {
      SystemDefinition systemDefinition = (SystemDefinition) iterator.next();
      for (Iterator iterator1 = systemDefinition.getAspectDefinitions().iterator();
          iterator1.hasNext(); ) {
        AspectDefinition aspectDef = (AspectDefinition) iterator1.next();
        if (aspectClass.getName().replace('/', '.').equals(aspectDef.getClassName())) {
          aspectDefinition = aspectDef;
          break;
        }
      }
    }
    if (aspectDefinition == null) {
      throw new Error("Could not find AspectDefinition for " + aspectClass.getName());
    }

    String containerClassName = aspectDefinition.getContainerClassName();
    try {
      Class containerClass;
      if (containerClassName == null
          || aspectClass.getName().equals(CFlowSystemAspect.CLASS_NAME)) {
        containerClass =
            ContextClassLoader.loadClass(aspectClass.getClassLoader(), DEFAULT_ASPECT_CONTAINER);
      } else {
        containerClass =
            ContextClassLoader.loadClass(aspectClass.getClassLoader(), containerClassName);
      }
      Constructor constructor = containerClass.getConstructor(new Class[] {AspectContext.class});
      final AspectContext aspectContext =
          new AspectContext(
              aspectDefinition.getSystemDefinition().getUuid(),
              aspectClass,
              aspectDefinition.getName(),
              DeploymentModel.getDeploymentModelAsInt(aspectDefinition.getDeploymentModel()),
              aspectDefinition,
              aspectDefinition.getParameters());
      final AspectContainer container =
          (AspectContainer) constructor.newInstance(new Object[] {aspectContext});
      aspectContext.setContainer(container);
      return container;
    } catch (InvocationTargetException e) {
      throw new DefinitionException(e.getTargetException().toString());
    } catch (NoSuchMethodException e) {
      throw new DefinitionException(
          "aspect container does not have a valid constructor ["
              + containerClassName
              + "] need to take an AspectContext instance as its only parameter: "
              + e.toString());
    } catch (Throwable e) {
      StringBuffer cause = new StringBuffer();
      cause.append("could not create aspect container using the implementation specified [");
      cause.append(containerClassName);
      cause.append("] due to: ");
      cause.append(e.toString());
      e.printStackTrace();
      throw new DefinitionException(cause.toString());
    }
  }
Пример #22
0
  /**
   * Performs intraprocedural BLOAT on a program's live methods.
   *
   * @param liveMethods Should be alphabetized. This way we can commit a class once we've BLOATed
   *     all of its methods.
   */
  private static void intraBloat(final Collection liveMethods, final BloatContext context) {

    ClassEditor prevClass = null;
    final Iterator iter = liveMethods.iterator();
    for (int count = 0; iter.hasNext(); count++) {
      MethodEditor live = null;
      ClassEditor ce = null; // Hack to make sure commit happens
      try {
        live = context.editMethod((MemberRef) iter.next());
        ce = context.editClass(live.declaringClass().classInfo());

      } catch (final NoSuchMethodException ex3) {
        BloatBenchmark.err.println("** Could not find method " + ex3.getMessage());
        System.exit(1);
      }

      /* So we can skip classes or packages */
      final String name = ce.type().className();
      final String qual = ce.type().qualifier() + "/*";
      boolean skip = false;
      for (int i = 0; i < BloatBenchmark.SKIP.size(); i++) {
        final String pkg = (String) BloatBenchmark.SKIP.get(i);

        if (name.equals(pkg) || qual.equals(pkg)) {
          skip = true;
          break;
        }
      }

      if (context.ignoreMethod(live.memberRef()) || skip) {
        // Don't display ignored methods, it's misleading.
        context.release(live.methodInfo());
        continue;
      }

      final Runtime runtime = Runtime.getRuntime();
      runtime.gc();

      final Date start = new Date();
      BloatBenchmark.tr(
          "  " + count + ") " + live.declaringClass().name() + "." + live.name() + live.type());
      BloatBenchmark.tr("    Start: " + start);

      try {
        EDU.purdue.cs.bloat.optimize.Main.TRACE = BloatBenchmark.TRACE;
        if (!BloatBenchmark.VERIFY) {
          EDU.purdue.cs.bloat.optimize.Main.VERIFY = false;
        }
        EDU.purdue.cs.bloat.optimize.Main.bloatMethod(live, context);

      } catch (final Exception oops) {
        BloatBenchmark.err.println("******************************************");
        BloatBenchmark.err.println(
            "Exception while BLOATing "
                + live.declaringClass().name()
                + "."
                + live.name()
                + live.type());
        BloatBenchmark.err.println(oops.getMessage());
        oops.printStackTrace(System.err);
        BloatBenchmark.err.println("******************************************");
      }

      // Commit here in an attempt to conserve memory
      context.commit(live.methodInfo());
      context.release(live.methodInfo());

      if (prevClass == null) {
        prevClass = ce;

      } else if (!prevClass.equals(ce)) {
        // We've finished BLOATed the methods for prevClass, commit
        // prevClass and move on
        BloatBenchmark.tr(prevClass.type() + " != " + ce.type());
        context.commit(prevClass.classInfo());
        context.release(prevClass.classInfo());
        // context.commitDirty();
        // tr(context.toString());
        prevClass = ce;

      } else {
        context.release(ce.classInfo());
      }

      final Date end = new Date();
      BloatBenchmark.tr("    Ellapsed time: " + (end.getTime() - start.getTime()) + " ms");
    }

    context.commitDirty();
  }