/** 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);
      }
    }
  }
Esempio n. 2
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();
   }
 }
Esempio n. 3
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;
  }
Esempio n. 5
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;
    }
  }
Esempio n. 6
0
 /**
  * Writes the object-graph containing values (primitives and wrappers), objects, and arrays,
  * starting from the given <code>o</code> node.
  *
  * @param o the write start-point node
  * @throws IllegalArgumentException if an illegal (non values/bean/array) is encountered
  */
 public final void write(Object o) {
   this.ensureRootWritten();
   try {
     this.write0(o);
   } catch (NoSuchMethodException nDC) {
     throw new IllegalArgumentException("o: no default constructor: " + nDC.getMessage(), nDC);
   } catch (InvocationTargetException | InstantiationException iDC) {
     throw new IllegalArgumentException(
         "o: invalid default constructor: " + iDC.getMessage(), iDC);
   } catch (IllegalAccessException iDCM) {
     throw new IllegalArgumentException(
         "o: invalid default constructor modifier: " + iDCM.getMessage(), iDCM);
   }
 }
  /** 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);
      }
    }
  }
Esempio n. 8
0
 /**
  * Writes the given object recursively.
  *
  * @param o to write
  */
 @Override
 public final void write(Object o) {
   if (this.state != Driver.STATE_START && this.state != Driver.STATE_VALUE) {
     throw new IllegalStateException("cannot write o");
   }
   try {
     this.target.write0(o);
   } catch (NoSuchMethodException nDC) {
     throw new IllegalArgumentException(
         "value: no default constructor: " + nDC.getMessage(), nDC);
   } catch (InvocationTargetException | InstantiationException iDC) {
     throw new IllegalArgumentException(
         "value: invalid default constructor: " + iDC.getMessage(), iDC);
   } catch (IllegalAccessException iDCM) {
     throw new IllegalArgumentException(
         "value: invalid default constructor modifier: " + iDCM.getMessage(), iDCM);
   }
 }
 /**
  * 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);
   }
 }
  /**
   * 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);
  }
Esempio n. 11
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);
      }
    }
  }
    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;
      }
    }
Esempio n. 13
0
  /**
   * Read V2tag if exists
   *
   * <p>TODO:shouldn't we be handing TagExceptions:when will they be thrown
   *
   * @param file
   * @param loadOptions
   * @throws IOException
   * @throws TagException
   */
  private void readV2Tag(File file, int loadOptions, int startByte)
      throws IOException, TagException {
    // We know where the actual Audio starts so load all the file from start to that point into
    // a buffer then we can read the IDv2 information without needing any more File I/O
    if (startByte >= AbstractID3v2Tag.TAG_HEADER_LENGTH) {
      logger.finer("Attempting to read id3v2tags");
      FileInputStream fis = null;
      FileChannel fc = null;
      ByteBuffer bb;
      try {
        fis = new FileInputStream(file);
        fc = fis.getChannel();
        bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, startByte);
      }
      // #JAUDIOTAGGER-419:If reading networked file map can fail so just copy bytes instead
      catch (IOException ioe) {
        bb = ByteBuffer.allocate(startByte);
        fc.read(bb, 0);
      } finally {
        if (fc != null) {
          fc.close();
        }

        if (fis != null) {
          fis.close();
        }
      }

      try {
        bb.rewind();

        if ((loadOptions & LOAD_IDV2TAG) != 0) {
          logger.config("Attempting to read id3v2tags");
          try {
            this.setID3v2Tag(new ID3v24Tag(bb, file.getName()));
          } catch (TagNotFoundException ex) {
            logger.config("No id3v24 tag found");
          }

          try {
            if (id3v2tag == null) {
              this.setID3v2Tag(new ID3v23Tag(bb, file.getName()));
            }
          } catch (TagNotFoundException ex) {
            logger.config("No id3v23 tag found");
          }

          try {
            if (id3v2tag == null) {
              this.setID3v2Tag(new ID3v22Tag(bb, file.getName()));
            }
          } catch (TagNotFoundException ex) {
            logger.config("No id3v22 tag found");
          }
        }
      } finally {
        // Workaround for 4724038 on Windows
        bb.clear();
        if (bb.isDirect() && !TagOptionSingleton.getInstance().isAndroid()) {
          // Reflection substitute for following code:
          //    ((sun.nio.ch.DirectBuffer) bb).cleaner().clean();
          // which causes exception on Android - Sun NIO classes are not available
          try {
            Class<?> clazz = Class.forName("sun.nio.ch.DirectBuffer");
            Method cleanerMethod = clazz.getMethod("cleaner");
            Object cleaner = cleanerMethod.invoke(bb); // cleaner = bb.cleaner()
            if (cleaner != null) {
              Method cleanMethod = cleaner.getClass().getMethod("clean");
              cleanMethod.invoke(cleaner); // cleaner.clean()
            }
          } catch (ClassNotFoundException e) {
            logger.severe("Could not load sun.nio.ch.DirectBuffer.");
          } catch (NoSuchMethodException e) {
            logger.severe("Could not invoke DirectBuffer method - " + e.getMessage());
          } catch (InvocationTargetException e) {
            logger.severe("Could not invoke DirectBuffer method - target exception");
          } catch (IllegalAccessException e) {
            logger.severe("Could not invoke DirectBuffer method - illegal access");
          }
        }
      }
    } else {
      logger.config("Not enough room for valid id3v2 tag:" + startByte);
    }
  }
Esempio n. 14
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;
 }
Esempio n. 15
0
 public Object __parse_response__(String resp) throws RemoteException {
   JsonParser parser = new JsonParser();
   JsonElement main_response = (JsonElement) parser.parse(resp);
   if (main_response.isJsonArray()) {
     List<Object> res = new Vector<Object>();
     for (Object o : main_response.getAsJsonArray()) {
       res.add(__parse_response__(gson.toJson(o)));
     }
     return res;
   }
   JsonObject response = main_response.getAsJsonObject();
   if (response.has("error")) {
     JsonObject e = response.get("error").getAsJsonObject().get("data").getAsJsonObject();
     throw new RemoteException(e.get("exception").getAsString(), e.get("message").getAsString());
   }
   JsonElement value = response.get("result");
   String valuestr = gson.toJson(response.get("result"));
   if (valuestr.contains("hash:")) {
     Class<? extends RpcClient> klass = this.getClass();
     try {
       Constructor<? extends RpcClient> m =
           klass.getDeclaredConstructor(String.class, String.class);
       String new_endpoint = gson.fromJson(value, String.class);
       return m.newInstance(this.base_endpoint, new_endpoint.replace("hash:", ""));
     } catch (NoSuchMethodException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     } catch (IllegalArgumentException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     } catch (InstantiationException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     } catch (IllegalAccessException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     } catch (InvocationTargetException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     }
   } else if (valuestr.contains("funcs")) {
     return gson.fromJson(valuestr, Interface.class);
   }
   if (value.isJsonPrimitive()) {
     JsonPrimitive val = value.getAsJsonPrimitive();
     if (val.isBoolean()) {
       return val.getAsBoolean();
     } else if (val.isNumber()) {
       return val.getAsNumber();
     } else if (val.isString()) {
       DateTimeFormatter dtparser = ISODateTimeFormat.dateHourMinuteSecond();
       try {
         return dtparser.parseDateTime(val.getAsString());
       } catch (Exception ex) {
       }
       return val.getAsString();
     } else {
       return null;
     }
   } else if (value.isJsonNull()) {
     return null;
   } else if (value.isJsonObject() && !value.getAsJsonObject().has("__meta__")) {
     return gson.fromJson(value, HashMap.class);
   } else if (value.isJsonArray()) {
     if (value.getAsJsonArray().size() == 0) return new LinkedList();
     JsonElement obj = value.getAsJsonArray().get(0);
     if (obj.isJsonObject()) {
       if (!obj.getAsJsonObject().has("__meta__")) {
         return gson.fromJson(value, LinkedList.class);
       }
     }
   }
   return __resolve_references__(valuestr);
 }
Esempio n. 16
0
  public boolean connect(Onion options, OobdBus receiveListener) {
    msgReceiver = receiveListener;
    System.out.println("Starting Bluetooth Detection and Device Pairing");
    if (mBluetoothAdapter == null) {
      mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
      if (mBluetoothAdapter == null) {
        Log.w(this.getClass().getSimpleName(), "Bluetooth not supported.");
        return false;
      }
      if (!mBluetoothAdapter.isEnabled()) {
        Log.w(this.getClass().getSimpleName(), "Bluetooth switched off.");
        return false;
      }
    }

    obdDevice = mBluetoothAdapter.getRemoteDevice(BTAddress);

    if (obdDevice != null) { // Get a BluetoothSocket to connect
      // with the given BluetoothDevice
      try {
        Log.v(this.getClass().getSimpleName(), "Device " + obdDevice.getName());
        java.lang.reflect.Method m =
            obdDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
        // "createInsecureRfcommSocket", new Class[] { int.class });
        serialPort = null;
        serialPort = (BluetoothSocket) m.invoke(obdDevice, 1);

        if (serialPort != null) {
          try {
            mBluetoothAdapter.cancelDiscovery();
            serialPort.connect();
            Log.d("OOBD:Bluetooth", "Bluetooth connected");
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();

            OOBDApp.getInstance().displayToast("Bluetooth connected");

            myThread =
                new Thread() {

                  @Override
                  public void run() {
                    byte[] buffer = new byte[1024]; // buffer store
                    // for the
                    // stream
                    int bytes; // bytes returned from read()

                    // Keep listening to the InputStream until an
                    // exception occurs
                    Log.d("OOBD:Bluetooth", "receiver task runs");
                    while (true) {
                      if (inputStream != null) {
                        try {
                          // Read from the InputStream
                          bytes = inputStream.read(buffer);
                          if (bytes > 0) {
                            Log.v(this.getClass().getSimpleName(), "Debug: received something");
                            String recString = new String(buffer);
                            recString = recString.substring(0, bytes);
                            msgReceiver.receiveString(recString);
                          }
                        } catch (IOException e) {
                          break;
                        }
                      } else {
                        try {
                          Thread.sleep(100);
                        } catch (InterruptedException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                        }
                      }
                    }
                  }
                };
            myThread.start();
            return true;
          } catch (IOException ex) {
            Log.e(this.getClass().getSimpleName(), "Error: Could not connect to socket.", ex);
            OOBDApp.getInstance().displayToast("Bluetooth NOT connected!");
          }
        } else {
          Log.e("OOBD:Bluetooth", "Bluetooth NOT connected!");
          OOBDApp.getInstance().displayToast("Bluetooth NOT connected!");
          if (serialPort != null) {
            try {
              serialPort.close();
            } catch (IOException closeEx) {
            }
          }
          return false;
        }
        // do not yet connect. Connect before calling the
        // socket.
      } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return false;
  }
Esempio n. 17
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();
  }