Exemple #1
0
 /**
  * 编译给定文件绝对路径的java文件列表
  *
  * @param srcFiles
  * @throws Exception
  */
 private void compile(String[] srcFiles) throws Exception {
   String args[] = this.buildCompileJavacArgs(srcFiles);
   ByteArrayOutputStream err = new ByteArrayOutputStream();
   JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
   if (compiler == null) {
     throw new NullPointerException(
         "ToolProvider.getSystemJavaCompiler() return null,please use JDK replace JRE!");
   }
   int resultCode = compiler.run(null, null, err, args);
   if (resultCode != 0) {
     throw new Exception(err.toString());
   }
 }
    // Writes the program to a source file, compiles it, and runs it.
    private void compileAndRun(String fileName, String code) {
      // Exceptions here can pick and choose what font to use, as needed.
      // Exceptions thrown by the program, that cause the Playground to be unstable, should be in
      // blue.

      println("Deleting old temp files...", progErr);
      new File(fileName + ".java").delete();
      new File(fileName + ".class").delete();

      println("Creating source file...", progErr);
      file = new File(fileName + ".java");

      println("Writing code to source file...", progErr);
      try {
        new FileWriter(file).append(code).close();
      } catch (IOException i) {
        println("Had an IO Exception when trying to write the code. Stack trace:", error);
        i.printStackTrace();
        return; // Exit on error
      }

      println("Compiling code...", progErr);
      // This should only ever be called if the JDK isn't installed. How you'd get here, I don't
      // know.
      if (compiler == null) {
        println("Fatal Error: JDK not installed. Go to java.sun.com and install.", error);
        return;
      }

      // Tries to compile. Success code is 0, so if something goes wrong, do stuff.
      int result =
          compiler.run(
              null,
              null,
              null,
              file
                  .getAbsolutePath()); // Possibly add a new outputstream to parse through the
                                       // compiler errors
      if (result != 0) {
        displayLog();
        println("Failed to compile.", error);
        return; // Return on error
      }

      println("Code compiled with 0 errors.", progErr);

      println("Attempting to run code...", progErr);
      run(fileName);
    }
 public static void main(String... args) {
   JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
   JFileChooser fileChooser;
   Preferences prefs = Preferences.userNodeForPackage(Launcher.class);
   if (args.length > 0) fileChooser = new JFileChooser(args[0]);
   else {
     String fileName = prefs.get("recent.file", null);
     fileChooser = new JFileChooser();
     if (fileName != null) {
       fileChooser = new JFileChooser();
       fileChooser.setSelectedFile(new File(fileName));
     }
   }
   if (fileChooser.showOpenDialog(null) == fileChooser.APPROVE_OPTION) {
     String fileName = fileChooser.getSelectedFile().getPath();
     prefs.put("recent.file", fileName);
     javac.run(System.in, null, null, "-d", "/tmp", fileName);
   }
 }
  public static void main(String[] args) {
    String example = "basic";
    String folder = "F:\\epclaimcodes\\shop2\\" + example + "\\";
    String domainFileName = folder + example;
    String problemFileName = folder + "problem";
    File file = new File(domainFileName);
    System.out.println(file.getPath());
    try {
      InternalDomain internalDomain = new InternalDomain(new File(domainFileName), -1);
      internalDomain.getParser().domain();
      InternalDomain internalDomainProblem = new InternalDomain(new File(problemFileName), 1);
      internalDomainProblem.getParser().command();
      JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
      File problemJavaFile = new File(folder + "problem.java");
      System.out.println(problemJavaFile.getPath());
      System.out.println("Compiler Status: " + compiler);
      String classPath = folder + ";F:\\EPClaim\\ClientWorkspace\\EPClaim\\bin";
      System.out.println("Class Path: " + classPath);
      compiler.run(null, null, null, (new File(folder + example + ".java")).getPath());
      compiler.run(
          null,
          null,
          null,
          "-classpath",
          classPath,
          "-sourcepath",
          folder,
          problemJavaFile.getPath());

      System.out.println("Done");

    } catch (IOException | RecognitionException | TokenStreamException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    ArrayList<String> classFiles = new ArrayList<String>();

    ClassLoader classLoader = ProblemClassLoader.class.getClassLoader();
    ProblemClassLoader problemClassLoader = new ProblemClassLoader(classLoader);
    try {
      File folderToLoad = new File(folder);
      for (File f : folderToLoad.listFiles()) {
        String classFileName = f.getName();
        if (classFileName.endsWith(".class")) {
          String classFileNameWithoutDotClass =
              classFileName.substring(0, classFileName.length() - 6);
          classFiles.add(classFileNameWithoutDotClass);
          System.out.println(classFileNameWithoutDotClass);
        }
      }
      Class<?> problem = null;
      ArrayList<Class<?>> allClasses = new ArrayList<Class<?>>();
      for (String className : classFiles) {
        Class<?> dummy = problemClassLoader.loadClass(className, folder);
        if (className.equals("problem")) problem = dummy;
        allClasses.add(dummy);
      }

      // Class<?> problem = problemClassLoader.loadClass("problem",folder);
      Method method = problem.getMethod("getPlans", null);
      LinkedList<Plan> plans = (LinkedList<Plan>) method.invoke(null, null);
      System.out.println("aClass.getName() = " + problem.getName());
      System.out.println("Plans: " + plans);
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SecurityException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemple #5
0
  public List<MuJavaInput> execute(MuJavaInput input) {

    File fileToMutate;
    String methodToCheck;
    HashSet<Mutant> mutOps;
    int generationsLeft;
    MuJavaInput muJavaInput;

    fileToMutate = new File(input.getFilename());
    if (!fileToMutate.exists()) {
      throw new IllegalStateException(
          "The file " + input.getFilename() + " doesn't exist. Can't continue.");
      //				return Lists.newArrayList();
    }
    methodToCheck = input.getMethod();
    mutOps = Sets.newHashSet(input.getMutantsToApply());
    classToMutate = obtainClassNameFromFileName(input.getFilename());
    generationsLeft = input.getQtyOfGenerations().get();
    muJavaInput = input;

    final File tmpDir = createWorkingDirectory();

    log.debug("Generating mutants...");
    MutantsInformationHolder genMutants =
        generateMutants(fileToMutate, methodToCheck, mutOps, classToMutate);

    //			log.warn("MutantCount: " +
    // mutantCount.addAndGet(genMutants.getMutantsIdentifiers().size()));

    log.debug(
        "Generation finished. Generated mutants: " + genMutants.getMutantsIdentifiers().size());
    List<MuJavaInput> nextGenerationInputs =
        new ArrayList<MuJavaInput>(genMutants.getMutantsIdentifiers().size());

    //			OpenJMLController outputController = OpenJMLController.getInstance();

    log.debug("Creating files for mutants");
    for (MutantIdentifier mutantIdentifier : genMutants.getMutantsIdentifiers()) {
      log.debug("Check that mutant is unique: " + mutantIdentifier);
      String dirString = tmpDir.toString();
      File tempFile =
          createTempFile(
              classToMutate,
              generationsLeft,
              privateI++,
              fileToMutate.getName().substring(0, 8),
              tmpDir,
              "a" + dirString.substring(dirString.lastIndexOf(FILE_SEP) + 1).replaceAll("-", ""));
      DigestOutputStream digestOutputStream = getDigestOutputStream(tempFile);
      int mutatedLine = writeMutant(genMutants.getCompUnit(), mutantIdentifier, digestOutputStream);

      MsgDigest msgDigest = new MsgDigest(digestOutputStream.getMessageDigest().digest());
      log.debug("generationsLeft= " + generationsLeft);
      log.debug("fileToMutate= " + fileToMutate);
      log.trace("fileToMutate.getAbsolutePath()= " + fileToMutate.getAbsolutePath());
      log.trace("mutatedLine= " + mutatedLine);
      log.trace(
          "filenameToMutatedLine.get(fileToMutate.getAbsolutePath())= "
              + filenameToMutatedLine.get(fileToMutate.getAbsolutePath()));
      Integer lastMutatedLine = filenameToMutatedLine.get(fileToMutate.getAbsolutePath());
      log.debug("last mutated line = " + lastMutatedLine);
      if (
      /*generationsLeft != 0
      &&*/ (lastMutatedLine != null && (lastMutatedLine > mutatedLine)
          || filesHash.containsKey(msgDigest))) {
        if (lastMutatedLine != null) {
          log.debug("lastmutadtedline > mutadtedline = " + (lastMutatedLine > mutatedLine));
        } else {
          log.debug("lastmutadtedline  = null");
        }
        log.debug("filesHash.containsKey(msgDigest) = " + filesHash.containsKey(msgDigest));
        if (EXTRA_CHECK && filesHash.containsKey(msgDigest)) {
          if (isFalseDuplicate(filesHash.get(msgDigest), tempFile)) {
            // If it is a false duplicate we don't have to delete
            // the file
            log.debug("False duplicated file");
            continue;
          }
        }
        // We have to delete this new mutant since it will be a
        // duplicate
        log.debug("Duplicated file");
        //					mutantCount.decrementAndGet();
        if (!tempFile.delete()) {
          log.error("Couldn't remove file " + tempFile.getName());
        }
        continue;
      }

      String currentClasspath =
          System.getProperty("java.class.path")
              + OpenJMLController.PATH_SEP
              + System.getProperty("user.dir")
              + FILE_SEP
              + "generated";

      JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
      int compilationResult =
          javaCompiler.run(
              null,
              new NullOutputStream(),
              new NullOutputStream(),
              new String[] {"-classpath", currentClasspath, tempFile.getAbsolutePath()});

      if (compilationResult == 0) {
        log.info("Compilation succeeded. Adding this file");

        filesHash.put(msgDigest, tempFile.getAbsolutePath());
        filenameToMutatedLine.put(tempFile.getAbsolutePath(), mutatedLine);
        OpenJMLInput output =
            new OpenJMLInput(
                tempFile.getAbsolutePath(),
                muJavaInput.getJunitInputs(),
                muJavaInput.getMethod(),
                muJavaInput.getConfigurationFile(),
                muJavaInput.getOverridingProperties(),
                muJavaInput.getOriginalFilename());
        log.debug("Adding task to the list");
        jmlInputs.add(output);
        if ((generationsLeft - 1) > 0) {
          int newNumberOfGenerations = generationsLeft - 1;
          //						log.warn("nuevo mutante: "+newNumberOfGenerations);
          MuJavaInput mji =
              new MuJavaInput(
                  tempFile.getAbsolutePath(),
                  muJavaInput.getMethod(),
                  muJavaInput.getJunitInputs(),
                  muJavaInput.getMutantsToApply(),
                  new AtomicInteger(newNumberOfGenerations),
                  muJavaInput.getConfigurationFile(),
                  muJavaInput.getOverridingProperties(),
                  muJavaInput.getOriginalFilename(),
                  output);
          nextGenerationInputs.add(mji);
        }
        if (jmlInputs.size() >= maxMethodsInFile) {
          OpenJMLInputWrapper wrapper = createJMLInputWrapper(jmlInputs, classToMutate);
          log.info("Creating output for OpenJMLController");
          OpenJMLController.getInstance().enqueueTask(wrapper);
          log.debug("Adding task to the OpenJMLController");
          jmlInputs.clear();
        }
      }
      //			else {
      //				log.warn("Compilation failed. Ignoring this file. Compilations failed: " +
      // compilationFailCount.incrementAndGet() );
      //			}

    }
    return nextGenerationInputs;
  }
 private void WhenCompiled() {
   String CompilePath = "generated/" + tutorial.getTutorialName() + ".java";
   JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
   int result = compiler.run(null, null, null, CompilePath);
   System.out.println("Compile result code = " + result);
 }