Example #1
0
  private static UserPreferences readPreferences(Preferences settings, boolean defaultsToDisabled) {
    boolean atLeastOneEnabled = false;
    UserPreferences prefs = UserPreferences.createDefaultUserPreferences();
    DetectorFactoryCollection dfc = DetectorFactoryCollection.instance();

    for (DetectorFactory df : dfc.getFactories()) {
      boolean enable = false;

      if (!df.isHidden()) {
        for (BugPattern bp : df.getReportedBugPatterns()) {
          BugCategory c = dfc.getBugCategory(bp.getCategory());

          if (c.isHidden()) continue;

          enable |=
              settings.getBoolean(bp.getType(), !defaultsToDisabled && prefs.isDetectorEnabled(df));
        }
      }

      atLeastOneEnabled |= enable;
      prefs.enableDetector(df, enable);
    }

    return atLeastOneEnabled ? prefs : null;
  }
Example #2
0
  private static void printPluginUpdates(boolean verbose, int secondsToWait)
      throws InterruptedException {
    DetectorFactoryCollection dfc = DetectorFactoryCollection.instance();

    if (dfc.getUpdateChecker().updateChecksGloballyDisabled()) {
      if (verbose) {
        System.out.println();
        System.out.print("Update checking globally disabled");
      }
      return;
    }
    if (verbose) {
      System.out.println();
      System.out.print("Checking for plugin updates...");
    }
    FutureValue<Collection<UpdateChecker.PluginUpdate>> updateHolder = dfc.getUpdates();

    try {
      Collection<UpdateChecker.PluginUpdate> updates =
          updateHolder.get(secondsToWait, TimeUnit.SECONDS);
      if (updates.isEmpty()) {
        if (verbose) System.out.println("none!");
      } else {
        System.out.println();
        for (UpdateChecker.PluginUpdate update : updates) {
          System.out.println(update);
          System.out.println();
        }
      }
    } catch (TimeoutException e) {
      if (verbose) System.out.println("Timeout while trying to get updates");
    }
  }
Example #3
0
  public static boolean isEnabledByDefault(BugPattern bp) {
    DetectorFactoryCollection dfc = DetectorFactoryCollection.instance();

    for (DetectorFactory df : dfc.getFactories()) {
      if (df.getReportedBugPatterns().contains(bp)) {
        return UserPreferences.createDefaultUserPreferences().isDetectorEnabled(df);
      }
    }

    return false;
  }
 /**
  * Set the Bug Categories we are interested, if configured.
  *
  * <p>
  *
  * <ul>
  *   <li>CORRECTNESS
  *   <li>NOISE
  *   <li>SECURITY
  *   <li>BAD_PRACTICE
  *   <li>STYLE
  *   <li>PERFORMANCE
  *   <li>MALICIOUS_CODE
  *   <li>MT_CORRECTNESS
  *   <li>I18N
  *   <li>EXPERIMENTAL
  * </ul>
  *
  * @param prefs the {@link UserPreferences} instance.
  */
 public void setBugCatagories(final UserPreferences prefs) throws CoreException {
   final ProjectFilterSettings pfs = prefs.getFilterSettings();
   final String bugCatagories =
       this.configurator.getParameterValue(BUG_CATEGORIES, String.class, session, execution);
   if (bugCatagories == null) {
     log.debug("bugCatagories is null");
     return;
   }
   List<String> addBugCatagoriesList = Arrays.asList(StringUtils.split(bugCatagories, ","));
   List<String> availableBugCategories =
       new LinkedList<String>(DetectorFactoryCollection.instance().getBugCategories());
   if (addBugCatagoriesList.size() > 0) {
     for (String removeBugCategory : availableBugCategories) {
       pfs.removeCategory(removeBugCategory);
     }
   }
   final Set<String> removeBugCategoriesSet = new HashSet<String>();
   for (String bc : addBugCatagoriesList) {
     final String bcUpper = bc.toUpperCase();
     if (availableBugCategories.contains(bcUpper)) {
       pfs.addCategory(bcUpper);
     } else {
       log.debug(String.format("[%s]: Unknown Bug Catagory [%s]", LOG_PREFIX, bc));
     }
     if (pfs.getActiveCategorySet().contains(bcUpper)) {
       removeBugCategoriesSet.add(bcUpper);
     }
   }
 }
 public void setVisitors(final UserPreferences prefs) throws CoreException {
   final String visitors =
       this.configurator.getParameterValue(VISITORS, String.class, session, execution);
   if (visitors == null) {
     return;
   }
   List<String> detectorsList = Arrays.asList(StringUtils.split(visitors, ","));
   prefs.enableAllDetectors(false);
   final DetectorFactoryCollection dfc = DetectorFactoryCollection.instance();
   for (String d : detectorsList) {
     final DetectorFactory df = dfc.getFactory(d);
     if (df == null) {
       log.error(String.format("[%s]: IGNORING unknown detector [%s]", LOG_PREFIX, d));
     } else {
       prefs.enableDetector(df, true);
     }
   }
 }
Example #6
0
  public static void main(String[] argv) throws InterruptedException {

    if (!IS_DEVELOPMENT && RELEASE_CANDIDATE != 0) {
      throw new IllegalStateException(
          "Non developmental version, but is release candidate " + RELEASE_CANDIDATE);
    }
    if (argv.length == 0) {
      printVersion(false);
      return;
    }

    String arg = argv[0];

    if ("-release".equals(arg)) {
      System.out.println(RELEASE);
    } else if ("-date".equals(arg)) {
      System.out.println(DATE);
    } else if ("-props".equals(arg)) {
      System.out.println("release.base=" + RELEASE_BASE);
      System.out.println("release.number=" + COMPUTED_RELEASE);
      System.out.println("release.date=" + COMPUTED_DATE);
      System.out.println("plugin.release.date=" + COMPUTED_PLUGIN_RELEASE_DATE);
      System.out.println("eclipse.ui.version=" + COMPUTED_ECLIPSE_UI_VERSION);
      System.out.println("findbugs.website=" + WEBSITE);
      System.out.println("findbugs.downloads.website=" + DOWNLOADS_WEBSITE);
      System.out.println("findbugs.git.revision=" + GIT_REVISION);
    } else if ("-plugins".equals(arg)) {
      DetectorFactoryCollection.instance();
      for (Plugin p : Plugin.getAllPlugins()) {
        System.out.println("Plugin: " + p.getPluginId());
        System.out.println("  description: " + p.getShortDescription());
        System.out.println("     provider: " + p.getProvider());
        String version = p.getVersion();
        if (version != null && version.length() > 0) {
          System.out.println("      version: " + version);
        }
        String website = p.getWebsite();
        if (website != null && website.length() > 0) {
          System.out.println("      website: " + website);
        }
        System.out.println();
      }
    } else if ("-configuration".equals(arg)) {
      printVersion(true);
    } else {

      usage();
      System.exit(1);
    }
  }
 /**
  * Enables or disables a detector. This can only disable an entire detector (class-level), not
  * just one bug pattern.
  *
  * @param dotSeperatedDetectorClass A string with the dot-separated-class of the detector to
  *     enable/disable
  * @param enabled
  */
 protected void setDetector(String dotSeperatedDetectorClass, boolean enabled) {
   DetectorFactory factory =
       DetectorFactoryCollection.instance().getFactoryByClassName(dotSeperatedDetectorClass);
   if (factory == null) {
     if (enabled) {
       fail("Could not find a detector with class " + dotSeperatedDetectorClass);
     } else {
       System.err.println("Could not find a detector with class " + dotSeperatedDetectorClass);
     }
     return;
   }
   if (!enabled) {
     detectorsToReenable.add(dotSeperatedDetectorClass);
   }
   FindbugsPlugin.getUserPreferences(testIProject).enableDetector(factory, enabled);
 }
  /**
   * @param resource
   * @param monitor
   * @return
   */
  private IFindBugsEngine getEngine(IResource resource, IProgressMonitor monitor) {
    IFindBugsEngine engine = engines.get(resource.getProject());
    if (engine != null) {
      return engine;
    }

    IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1);
    subMonitor.subTask("Creating Findbugs-engine for " + resource.getProject().getName());

    engine = new FindBugs2();
    engine.setDetectorFactoryCollection(DetectorFactoryCollection.instance());
    engine.setUserPreferences(UserPreferences.createDefaultUserPreferences());
    engines.put(resource.getProject(), engine);

    subMonitor.done();
    return engine;
  }
Example #9
0
  private static UserPreferences forSingleBug(String id) {
    boolean atLeastOneEnabled = false;
    UserPreferences prefs = UserPreferences.createDefaultUserPreferences();

    for (DetectorFactory df : DetectorFactoryCollection.instance().getFactories()) {
      boolean enable = false;

      for (BugPattern bp : df.getReportedBugPatterns()) {
        if (id.equals(bp.getType())) {
          enable = true;
          break;
        }
      }

      atLeastOneEnabled |= enable;
      prefs.enableDetector(df, enable);
    }

    return atLeastOneEnabled ? prefs : null;
  }
Example #10
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;
  }