Ejemplo n.º 1
0
  /**
   * Search for reviewed violations in that file
   *
   * @param file
   */
  private List<Review> findReviewedViolations(final IFile file) {
    final List<Review> reviews = new ArrayList<Review>();
    BufferedReader reader = null;
    try {
      int lineNumber = 0;
      boolean findLine = false;
      boolean comment = false;
      final Stack<String> pendingReviews = new Stack<String>();
      reader = new BufferedReader(new InputStreamReader(file.getContents()));
      while (reader.ready()) {
        String line = reader.readLine();
        if (line != null) {
          line = line.trim();
          lineNumber++;
          if (line.startsWith("/*")) {
            comment = line.indexOf("*/") == -1;
          } else if (comment && line.indexOf("*/") != -1) {
            comment = false;
          } else if (!comment && line.startsWith(PMDRuntimeConstants.PLUGIN_STYLE_REVIEW_COMMENT)) {
            final String tail =
                line.substring(PMDRuntimeConstants.PLUGIN_STYLE_REVIEW_COMMENT.length());
            final String ruleName = tail.substring(0, tail.indexOf(':'));
            pendingReviews.push(ruleName);
            findLine = true;
          } else if (!comment
              && findLine
              && StringUtil.isNotEmpty(line)
              && !line.startsWith("//")) {
            findLine = false;
            while (!pendingReviews.empty()) {
              // @PMD:REVIEWED:AvoidInstantiatingObjectsInLoops:
              // by Herlin on 01/05/05 18:36
              final Review review = new Review();
              review.ruleName = pendingReviews.pop();
              review.lineNumber = lineNumber;
              reviews.add(review);
            }
          }
        }
      }

      // if (log.isDebugEnabled()) {
      // for (int i = 0; i < reviewsList.size(); i++) {
      // final Review review = (Review) reviewsList.get(i);
      // log.debug("Review : rule " + review.ruleName + ", line " +
      // review.lineNumber);
      // }
      // }

    } catch (CoreException e) {
      PMDPlugin.getDefault().logError("Core Exception when searching reviewed violations", e);
    } catch (IOException e) {
      PMDPlugin.getDefault().logError("IO Exception when searching reviewed violations", e);
    } finally {
      IOUtil.closeQuietly(reader);
    }

    return reviews;
  }
  /* @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent) */
  public void resourceChanged(IResourceChangeEvent event) {
    try {
      event
          .getDelta()
          .accept(
              new IResourceDeltaVisitor() {
                public boolean visit(final IResourceDelta delta) throws CoreException {
                  // find the resource for the path of the current page
                  IPath path = getResourcePath();
                  if (delta.getFullPath().equals(path)) {
                    Display.getDefault()
                        .asyncExec(
                            new Runnable() {
                              public void run() {
                                refresh(delta.getResource());
                              }
                            });

                    return false;
                  }
                  return true;
                }
              });
    } catch (CoreException e) {
      PMDPlugin.getDefault().logError(StringKeys.ERROR_CORE_EXCEPTION, e);
    }
  }
Ejemplo n.º 3
0
  /** Calculate the number of methods. */
  public void calculateNumberOfMethods() {
    if (resource.isAccessible()) {

      // we need to change the Resource into a Java-File
      final IJavaElement element = JavaCore.create(resource);
      final List<Object> methods = new ArrayList<Object>();

      if (element instanceof ICompilationUnit) {
        try {
          // ITypes can be Package Declarations or other Java Stuff too
          IType[] types = ((ICompilationUnit) element).getTypes();
          for (IType type : types) {
            // only if it is an IType itself, it's a Class
            // from which we can get its Methods
            methods.addAll(Arrays.asList(type.getMethods()));
          }
        } catch (JavaModelException jme) {
          PMDPlugin.getDefault().logError(StringKeys.ERROR_JAVAMODEL_EXCEPTION + toString(), jme);
        }
      }
      if (!methods.isEmpty()) {
        numberOfMethods = methods.size();
      }
    }
  }
Ejemplo n.º 4
0
  public List<Renderer> activeRenderers() {

    List<Renderer> actives = new ArrayList<Renderer>();
    IPreferences prefs = PMDPlugin.getDefault().loadPreferences();

    for (Renderer renderer : allRenderers) {
      if (prefs.isActiveRenderer(renderer.getName())) actives.add(renderer);
    }

    return actives;
  }
Ejemplo n.º 5
0
  /**
   * Finds PMD PDFA Markers in the File
   *
   * @return an Array of markers
   */
  public IMarker[] findDFAMarkers() {

    try {
      // we can only find Markers for a file
      // we use the DFA-Marker-ID set for Dataflow Anomalies
      if (resource.isAccessible()) {
        return MarkerUtil.findMarkers(resource, PMDRuntimeConstants.PMD_DFA_MARKER);
      }
    } catch (CoreException ce) {
      PMDPlugin.getDefault().logError(StringKeys.ERROR_FIND_MARKER + this.toString(), ce);
    }

    return MarkerUtil.EMPTY_MARKERS;
  }
Ejemplo n.º 6
0
  /**
   * Reads a Resource's File and return the Code as String.
   *
   * @param resource a resource to read ; the resource must be accessible.
   * @return a String which is the Files Content
   */
  protected String resourceToString(IResource resource) {
    final StringBuilder fileContents = new StringBuilder();
    BufferedReader bReader = null;
    try {
      // we create a FileReader
      bReader = new BufferedReader(new FileReader(resource.getRawLocation().toFile()));

      // ... and read the File line by line
      while (bReader.ready()) {
        fileContents.append(bReader.readLine()).append('\n');
      }
    } catch (FileNotFoundException fnfe) {
      PMDPlugin.getDefault()
          .logError(
              StringKeys.ERROR_FILE_NOT_FOUND + resource.toString() + " in " + this.toString(),
              fnfe);
    } catch (IOException ioe) {
      PMDPlugin.getDefault().logError(StringKeys.ERROR_IO_EXCEPTION + this.toString(), ioe);
    } finally {
      IOUtil.closeQuietly(bReader);
    }

    return fileContents.toString();
  }
Ejemplo n.º 7
0
  /**
   * Finds PMD-Markers in the File
   *
   * @return an Array of markers
   */
  @Override
  public final IMarker[] findMarkers() {

    try {
      // this is the overwritten Function from AbstractPMDRecord
      // we simply call the IResource-function to find Markers
      if (resource.isAccessible()) {
        return MarkerUtil.findMarkers(resource, PMDRuntimeConstants.RULE_MARKER_TYPES);
      }
    } catch (CoreException ce) {
      PMDPlugin.getDefault().logError(StringKeys.ERROR_FIND_MARKER + this.toString(), ce);
    }

    return MarkerUtil.EMPTY_MARKERS;
  }
Ejemplo n.º 8
0
  /**
   * Finds Markers, that have a given Attribute with a given Value
   *
   * @param attributeName
   * @param value
   * @return an Array of markers matching these Attribute and Value
   */
  @Override
  public IMarker[] findMarkersByAttribute(String attributeName, Object value) {
    final IMarker[] markers = findMarkers();
    final List<IMarker> attributeMarkers = new ArrayList<IMarker>();
    try {
      // we get all Markers and catch the ones that matches our criteria
      for (IMarker marker : markers) {
        final Object val = marker.getAttribute(attributeName);

        // if the value is null, the Attribute doesn't exist
        if (val != null && val.equals(value)) {
          attributeMarkers.add(marker);
        }
      }
    } catch (CoreException ce) {
      PMDPlugin.getDefault().logError(StringKeys.ERROR_FIND_MARKER + this.toString(), ce);
    }

    // return an Array of the Markers
    return attributeMarkers.toArray(new IMarker[attributeMarkers.size()]);
  }
Ejemplo n.º 9
0
  /** @see net.sourceforge.pmd.eclipse.ui.model.AbstractPMDRecord#createChildren() */
  @Override
  protected final AbstractPMDRecord[] createChildren() {
    AbstractPMDRecord[] children = EMPTY_RECORDS;

    try { // get all markers
      final List<IMarker> markers = Arrays.asList(findMarkers());
      if (markers.isEmpty()) return EMPTY_RECORDS;

      final Iterator<IMarker> markerIterator = markers.iterator();

      // put all markers in a map with key = rulename
      final Map<String, MarkerRecord> allMarkerMap = new HashMap<String, MarkerRecord>();
      while (markerIterator.hasNext()) {
        final IMarker marker = markerIterator.next();

        MarkerRecord markerRecord = allMarkerMap.get(MarkerUtil.ruleNameFor(marker));
        if (markerRecord == null) {
          String ruleName = MarkerUtil.ruleNameFor(marker);
          markerRecord =
              new MarkerRecord(
                  this, // NOPMD by Sven on 13.11.06 11:57
                  ruleName,
                  MarkerUtil.rulePriorityFor(marker));
          markerRecord.addViolation(marker);
          allMarkerMap.put(ruleName, markerRecord);
        } else {
          markerRecord.addViolation(marker);
        }
      }

      children = allMarkerMap.values().toArray(new MarkerRecord[allMarkerMap.size()]);
    } catch (CoreException e) {
      PMDPlugin.getDefault().logError(StringKeys.ERROR_CORE_EXCEPTION + this.toString(), e);
    }

    return children; // no children so return an empty array, not null!
  }
 protected static IPreferenceStore pStore() {
   return PMDPlugin.getDefault().getPreferenceStore();
 }
Ejemplo n.º 11
0
  /**
   * Run PMD against a resource
   *
   * @param resource the resource to process
   */
  protected final void reviewResource(IResource resource) {

    IFile file = (IFile) resource.getAdapter(IFile.class);
    if (file == null || file.getFileExtension() == null) return;

    Reader input = null;
    try {
      boolean included = isIncluded(file);
      log.debug("Derived files included: " + projectProperties.isIncludeDerivedFiles());
      log.debug("file " + file.getName() + " is derived: " + file.isDerived());
      log.debug("file checked: " + included);

      prepareMarkerAccumulator(file);

      LanguageVersionDiscoverer languageDiscoverer = new LanguageVersionDiscoverer();
      LanguageVersion languageVersion =
          languageDiscoverer.getDefaultLanguageVersionForFile(file.getName());
      // in case it is java, select the correct java version
      if (languageVersion != null && languageVersion.getLanguage() == Language.JAVA) {
        languageVersion = PMDPlugin.javaVersionFor(file.getProject());
      }
      if (languageVersion != null) {
        configuration().setDefaultLanguageVersion(languageVersion);
      }
      log.debug("discovered language: " + languageVersion);

      final File sourceCodeFile = file.getRawLocation().toFile();
      if (included
          && getRuleSet().applies(sourceCodeFile)
          && isFileInWorkingSet(file)
          && languageVersion != null) {
        subTask("PMD checking: " + file.getName());

        Timer timer = new Timer();

        RuleContext context = PMD.newRuleContext(file.getName(), sourceCodeFile);
        context.setLanguageVersion(languageVersion);

        input = new InputStreamReader(file.getContents(), file.getCharset());
        //                    getPmdEngine().processFile(input, getRuleSet(), context);
        //                    getPmdEngine().processFile(sourceCodeFile, getRuleSet(), context);

        RuleSets rSets = new RuleSets(getRuleSet());
        new SourceCodeProcessor(configuration()).processSourceCode(input, rSets, context);

        timer.stop();
        pmdDuration += timer.getDuration();

        updateMarkers(file, context, isUseTaskMarker());

        worked(1);
        fileCount++;
      } else {
        log.debug("The file " + file.getName() + " is not in the working set");
      }

    } catch (CoreException e) {
      log.error("Core exception visiting " + file.getName(), e); // TODO:		// complete message
    } catch (PMDException e) {
      log.error("PMD exception visiting " + file.getName(), e); // TODO: 		// complete message
    } catch (IOException e) {
      log.error("IO exception visiting " + file.getName(), e); // TODO: 		// complete message
    } catch (PropertiesException e) {
      log.error("Properties exception visiting " + file.getName(), e); // TODO:	// complete message
    } finally {
      IOUtil.closeQuietly(input);
    }
  }