/** 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);
      }
    }
  }
  /**
   * 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;
    }
  }
  /** 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);
      }
    }
  }
  /** 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);
      }
    }
  }
 /**
  * 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;
 }
    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;
      }
    }
  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;
  }
  /**
   * 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();
  }