예제 #1
0
  public static List<ErrorDescription> runFindBugs(
      CompilationInfo info,
      Preferences customSettings,
      String singleBug,
      FileObject sourceRoot,
      Iterable<? extends String> classNames,
      FindBugsProgress progress,
      SigFilesValidator validator) {
    List<ErrorDescription> result = new ArrayList<ErrorDescription>();

    try {
      Class.forName(
          "org.netbeans.modules.findbugs.NbClassFactory",
          true,
          RunFindBugs.class.getClassLoader()); // NOI18N
      Project p = new Project();
      URL[] binaryRoots =
          CacheBinaryForSourceQuery.findCacheBinaryRoots(sourceRoot.toURL()).getRoots();

      if (classNames == null) {
        for (URL binary : binaryRoots) {
          try {
            p.addFile(new File(binary.toURI()).getAbsolutePath());
          } catch (URISyntaxException ex) {
            Exceptions.printStackTrace(ex);
          }
        }
      } else {
        ClassPath binary = ClassPathSupport.createClassPath(binaryRoots);
        List<FileObject> sigFiles = new ArrayList<FileObject>();

        for (String className : classNames) {
          FileObject classFO = binary.findResource(className.replace('.', '/') + ".sig"); // NOI18N

          if (classFO != null) {
            sigFiles.add(classFO);
          } else {
            LOG.log(
                Level.WARNING,
                "Cannot find sig file for: "
                    + className); // TODO: should probably become FINE eventually
          }
        }

        assert validator != null;

        if (!validator.validate(sigFiles)) return null;

        for (FileObject classFO : sigFiles) {
          p.addFile(new File(classFO.toURI()).getAbsolutePath());
        }

        addCompileRootAsSource(p, sourceRoot);
      }

      ClassPath compile = ClassPath.getClassPath(sourceRoot, ClassPath.COMPILE);

      for (FileObject compileRoot : compile.getRoots()) {
        addCompileRoot(p, compileRoot);
      }

      BugCollectionBugReporter r =
          new BugCollectionBugReporter(p) {
            @Override
            protected void emitLine(String line) {
              LOG.log(Level.FINE, line);
            }
          };

      r.setPriorityThreshold(Integer.MAX_VALUE);
      r.setRankThreshold(Integer.MAX_VALUE);

      FindBugs2 engine = new FindBugs2();

      engine.setProject(p);
      engine.setNoClassOk(true);
      engine.setBugReporter(r);

      if (progress != null) {
        engine.setProgressCallback(progress);
      }

      boolean inEditor = validator != null;
      Preferences settings =
          customSettings != null
              ? customSettings
              : NbPreferences.forModule(RunFindBugs.class).node("global-settings");
      UserPreferences preferences;

      if (singleBug != null) {
        singleBug = singleBug.substring(PREFIX_FINDBUGS.length());
        preferences = forSingleBug(singleBug);
      } else {
        preferences = readPreferences(settings, customSettings != null);
      }

      if (preferences == null) {
        // nothing enabled, stop
        return result;
      }

      engine.setUserPreferences(preferences);
      engine.setDetectorFactoryCollection(DetectorFactoryCollection.instance());

      LOG.log(Level.FINE, "Running FindBugs");

      engine.execute();

      Map<FileObject, List<BugInstance>> file2Bugs = new HashMap<FileObject, List<BugInstance>>();

      for (BugInstance b : r.getBugCollection().getCollection()) {
        if (singleBug != null && !singleBug.equals(b.getBugPattern().getType())) continue;
        if (singleBug == null
            && !settings.getBoolean(
                b.getBugPattern().getType(),
                customSettings == null && isEnabledByDefault(b.getBugPattern()))) {
          continue;
        }

        SourceLineAnnotation sourceLine = b.getPrimarySourceLineAnnotation();
        FileObject sourceFile = null;

        if (sourceLine != null) {
          sourceFile = sourceRoot.getFileObject(sourceLine.getSourcePath());

          if (sourceFile != null) {
            List<BugInstance> bugs = file2Bugs.get(sourceFile);

            if (bugs == null) {
              file2Bugs.put(sourceFile, bugs = new ArrayList<BugInstance>());
            }

            bugs.add(b);
          } else {
            LOG.log(
                Level.WARNING,
                "{0}, location: {1}:{2}",
                new Object[] {b, sourceLine.getSourcePath(), sourceLine.getStartLine()});
          }
        }
      }

      for (Entry<FileObject, List<BugInstance>> e : file2Bugs.entrySet()) {
        int[] lineOffsets = null;
        FileObject sourceFile = e.getKey();
        DataObject d = DataObject.find(sourceFile);
        EditorCookie ec = d.getLookup().lookup(EditorCookie.class);
        Document doc = ec.getDocument();
        JavaSource js = null;

        for (BugInstance b : e.getValue()) {
          SourceLineAnnotation sourceLine = b.getPrimarySourceLineAnnotation();

          if (sourceLine.getStartLine() >= 0) {
            LazyFixList fixes =
                prepareFixes(b, inEditor, sourceFile, sourceLine.getStartLine(), null);

            if (doc != null) {
              result.add(
                  ErrorDescriptionFactory.createErrorDescription(
                      PREFIX_FINDBUGS + b.getType(),
                      Severity.VERIFIER,
                      b.getMessageWithoutPrefix(),
                      b.getBugPattern().getDetailHTML(),
                      fixes,
                      doc,
                      sourceLine.getStartLine()));
            } else {
              if (lineOffsets == null) {
                lineOffsets = computeLineMap(sourceFile, FileEncodingQuery.getEncoding(sourceFile));
              }

              int edLine = 2 * (Math.min(sourceLine.getStartLine(), lineOffsets.length / 2) - 1);

              result.add(
                  ErrorDescriptionFactory.createErrorDescription(
                      PREFIX_FINDBUGS + b.getType(),
                      Severity.VERIFIER,
                      b.getMessageWithoutPrefix(),
                      b.getBugPattern().getDetailHTML(),
                      fixes,
                      sourceFile,
                      lineOffsets[edLine],
                      lineOffsets[edLine + 1]));
            }
          } else {
            if (js == null) {
              js = JavaSource.forFileObject(sourceFile);
            }
            addByElementAnnotation(b, info, sourceFile, js, result, inEditor);
          }
        }
      }
    } catch (ClassNotFoundException ex) {
      Exceptions.printStackTrace(ex);
    } catch (IOException ex) {
      Exceptions.printStackTrace(ex);
    } catch (InterruptedException ex) {
      LOG.log(Level.FINE, null, ex);
    }

    return result;
  }
예제 #2
0
  public void reparse(Snapshot snapshot, String content) throws ParseException {
    LOG.warning("Thread id " + Thread.currentThread().getId());
    LOG.warning("Parsing document " + (count++));

    this.snapshot = snapshot;

    // mirahParser = new mirah.impl.MirahParser ();
    // mirahParser.parse(snapshot.getText().toString());
    diag = new MirahParseDiagnostics();
    Mirahc compiler = new Mirahc();

    // Project proj = snapshot.getSource().getFileObject().getLookup().lookup(Project.class);
    FileObject src = snapshot.getSource().getFileObject();
    // LOG.warning("Source file is "+src);
    ClassPath compileClassPath = ClassPath.getClassPath(src, ClassPath.COMPILE);
    // LOG.warning("Project directory is "+proj.getProjectDirectory().getName());
    // LOG.warning("Parsing classpath is "+compileClassPath.toString());

    ClassPath buildClassPath = ClassPath.getClassPath(src, ClassPath.EXECUTE);

    // LOG.warning("Execute classapth is "+buildClassPath.toString());

    ClassPath srcClassPath = ClassPath.getClassPath(src, ClassPath.SOURCE);
    // LOG.warning("Src classapth is "+srcClassPath.toString());

    compiler.setDestination(buildClassPath.toString());
    compiler.setDiagnostics(diag);

    List<String> paths = new ArrayList<String>();
    if (!"".equals(srcClassPath.toString())) {
      paths.add(srcClassPath.toString());
    }
    if (!"".equals(buildClassPath.toString())) {
      paths.add(buildClassPath.toString());
    }
    if (!"".equals(compileClassPath.toString())) {
      paths.add(compileClassPath.toString());
    }

    StringBuilder classPath = new StringBuilder();
    for (String path : paths) {
      classPath.append(path);
      classPath.append(File.pathSeparator);
    }

    String cp = ".";
    if (classPath.length() >= 1) {
      cp = classPath.toString().substring(0, classPath.length() - 1);
    }
    compiler.setClasspath(cp);
    DocumentDebugger debugger = new DocumentDebugger();

    compiler.setDebugger(debugger);

    ClassPath bootClassPath = ClassPath.getClassPath(src, ClassPath.BOOT);
    if (!"".equals(bootClassPath.toString())) {
      compiler.setBootClasspath(bootClassPath.toString());
    }
    String srcText = content;

    compiler.addFakeFile(src.getPath(), srcText);

    try {
      compiler.compile(new String[0]);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    LOG.warning("Finished parsing document");

    synchronized (documentDebuggers) {
      LOG.warning("Inside sync documentDebuggers");
      Document doc = snapshot.getSource().getDocument(true);
      LOG.warning("Resolved types " + debugger.resolvedTypes);
      if (debugger.resolvedTypes.size() > 0) {
        debugger.compiler = compiler;
        LOG.warning("NEW DOCUMENT DEBUGGER ADDED");
        documentDebuggers.put(doc, debugger);
        fireOnParse(doc);
      }
    }
  }
  boolean valid(WizardDescriptor wizard) {
    //        List<Entity> entities = (List<Entity>)
    // wizard.getProperty(WizardProperties.ENTITY_CLASS);
    //        String controllerPkg = getPackage();
    //
    //        boolean filesAlreadyExist = false;
    //        String troubleMaker = "";
    //        for (Entity entity : entities) {
    //            String entityClass = entity.getClass2();
    //            String simpleClassName = JSFClientGenerator.simpleClassName(entityClass);
    //            String firstLower = simpleClassName.substring(0, 1).toLowerCase() +
    // simpleClassName.substring(1);
    //            String folder = jsfFolder.getText().endsWith("/") ? jsfFolder.getText() :
    // jsfFolder.getText() + "/";
    //            folder = folder + firstLower;
    //            String controller = controllerPkg + "." + simpleClassName + "Controller";
    //            String fqn = getPackage().length() > 0 ? getPackage().replace('.', '/') + "/" +
    // simpleClassName : simpleClassName;
    //            if (getLocationValue().getRootFolder().getFileObject(fqn + "Controller.java") !=
    // null) {
    //                filesAlreadyExist = true;
    //                troubleMaker = controllerPkg + "." + simpleClassName + "Controller.java";
    //                break;
    //            }
    //            if (getLocationValue().getRootFolder().getFileObject(fqn + "Converter.java") !=
    // null) {
    //                filesAlreadyExist = true;
    //                troubleMaker = controllerPkg + "." + simpleClassName + "Converter.java";
    //                break;
    //            }
    //        }
    //        if (filesAlreadyExist) {
    //            wizard.putProperty("WizardPanel_errorMessage",                                  //
    // NOI18N
    //                NbBundle.getMessage(JpaControllerSetupPanelVisual.class,
    // "MSG_FilesAlreadyExist", troubleMaker));
    //            return false;
    //        }
    //        wizard.putProperty("WizardPanel_errorMessage", null); // NOI18N

    if (Util.isContainerManaged(project)) {
      ClassPath cp = ClassPath.getClassPath(getLocationValue().getRootFolder(), ClassPath.COMPILE);
      ClassLoader cl = cp.getClassLoader(true);
      try {
        Class.forName("javax.transaction.UserTransaction", false, cl);
      } catch (ClassNotFoundException cnfe) {
        wizard.putProperty(
            "WizardPanel_errorMessage",
            NbBundle.getMessage(
                JpaControllerSetupPanelVisual.class, "ERR_UserTransactionUnavailable"));
        return false;
      } catch (java.lang.UnsupportedClassVersionError err) {
        //                    wizard.putProperty("WizardPanel_errorMessage",
        // NbBundle.getMessage(JpaControllerSetupPanelVisual.class,
        // "ERR_UserTransactionJavaVersion"));
        //                    return false;
      }
    }

    //            Sources srcs = (Sources) project.getLookup().lookup(Sources.class);
    //            SourceGroup sgWeb[] = srcs.getSourceGroups("doc_root"); //NOI18N fixme(mbohm):
    // move into constant
    //            FileObject pagesRootFolder = sgWeb[0].getRootFolder();
    //            File pagesRootFolderAsFile = FileUtil.toFile(pagesRootFolder);
    //            String jsfFolderText = jsfFolder.getText();
    //            try {
    //                String canonPath = new File(pagesRootFolderAsFile,
    // jsfFolderText).getCanonicalPath();
    //            }
    //            catch (IOException ioe) {
    //                wizard.putProperty("WizardPanel_errorMessage",
    // NbBundle.getMessage(JpaControllerSetupPanelVisual.class,
    // "ERR_JsfTargetChooser_InvalidJsfFolder"));
    //                return false;
    //            }

    String packageName = getPackage();
    if (packageName.trim().equals("")) { // NOI18N
      wizard.putProperty(
          "WizardPanel_errorMessage",
          NbBundle.getMessage(
              JpaControllerSetupPanelVisual.class, "ERR_JavaTargetChooser_CantUseDefaultPackage"));
      return false;
    }

    if (!JavaIdentifiers.isValidPackageName(packageName)) {
      wizard.putProperty(
          "WizardPanel_errorMessage",
          NbBundle.getMessage(
              JpaControllerSetupPanelVisual.class,
              "ERR_JavaTargetChooser_InvalidPackage")); // NOI18N
      return false;
    }

    if (!SourceGroups.isFolderWritable(getLocationValue(), packageName)) {
      wizard.putProperty(
          "WizardPanel_errorMessage",
          NbBundle.getMessage(
              JpaControllerSetupPanelVisual.class,
              "ERR_JavaTargetChooser_UnwritablePackage")); // NOI18N
      return false;
    }
    wizard.putProperty("WizardPanel_errorMessage", null); // NOI18N
    return true;
  }