com.puppycrawl.tools.checkstyle.api.AuditEvent Java Examples

The following examples show how to use com.puppycrawl.tools.checkstyle.api.AuditEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DiffLineFilter.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Only accept events that corresponding to the diff edits
 *
 * @return True if the event is corresponding to the diff edits
 */
@Override
public boolean accept(AuditEvent event) {
    List<Edit> editList = fileEditMap.get(event.getFileName());
    if (CollectionUtils.isEmpty(editList)) {
        return false;
    }
    for (Edit edit : editList) {
        if (edit.getBeginB() < event.getLine() && edit.getEndB() >= event.getLine()) {
            return true;
        }
        if (isEmptyLineSeparatorCheck(event) && event.getLine() == edit.getEndB() + 1) {
            return true;
        }
    }
    return false;
}
 
Example #2
Source File: MetricCountExtractor.java    From coderadar with MIT License 6 votes vote down vote up
/**
 * Extracts the metric count from a Checkstyle AuditEvent.
 *
 * <p>An AuditEvent contains a message which describes some coding violation. Usually, each of
 * these messages represents a single violation. Some messages however represent a number of
 * violations. For example the message for CyclomaticComplexityCheck contains a complexity for a
 * method (if it is higher than a configured threshold, otherwise it is not reported).
 *
 * @param event the Checkstyle event to extract a metric count from.
 * @return the count of the metric that is reported by the Checkstyle event.
 */
public Long extractMetricCount(AuditEvent event) {
  try {

    if (event.getSourceName().equals(CyclomaticComplexityCheck.class.getName())) {
      return extractLongArgument(event, 0);
    } else if (event.getSourceName().equals(ReturnCountCheck.class.getName())) {
      return extractLongArgument(event, 0);
    } else if (event.getSourceName().equals(JavaNCSSCheck.class.getName())) {
      return extractLongArgument(event, 0);
    } else if (event.getSourceName().equals(NPathComplexityCheck.class.getName())) {
      return extractLongArgument(event, 0);
    } else if (event.getSourceName().equals(ExecutableStatementCountCheck.class.getName())) {
      return extractLongArgument(event, 0);
    }

    // by default return 1 which means we are just counting the events
    return 1L;
  } catch (NoSuchFieldException | IllegalAccessException e) {
    return -1L;
  }
}
 
Example #3
Source File: VerboseListener.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void fileStarted(AuditEvent aEvt)
{
    mErrors = 0;
    mWriter.println(
        "Started checking file '" + aEvt.getFileName() + "'.");
}
 
Example #4
Source File: VerboseListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void addException(AuditEvent aEvt, Throwable aThrowable)
{
    printEvent(aEvt);
    aThrowable.printStackTrace(System.out);
    mErrors++;
    mTotalErrors++;
}
 
Example #5
Source File: AssertionsAuditListener.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
@Override
public void addError(AuditEvent event) {
	recordLevel(event);
	if (event.getSeverityLevel() != SeverityLevel.IGNORE) {
		recordMessage(FORMATTER.format(event));
	}
}
 
Example #6
Source File: CheckstyleAuditListenerTest.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
private CheckstyleAuditListener addErrorToListener(AuditEvent auditEvent) {
    final CheckstyleAuditListener listener = new CheckstyleAuditListener(
            ruleFinder,
            fileSystem);
    listener.setContext(context);
    listener.addError(auditEvent);
    return listener;
}
 
Example #7
Source File: VerboseListener.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void addException(AuditEvent aEvt, Throwable aThrowable)
{
    printEvent(aEvt);
    aThrowable.printStackTrace(System.out);
    mErrors++;
    mTotalErrors++;
}
 
Example #8
Source File: RepositoryMinerAudit.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
@Override
public void fileStarted(AuditEvent event) {
	String filename = FilenameUtils.normalize(event.getFileName());
	filename = filename.substring(repositoryPathEnd);
	
	currFile = filename;
	fileErrors.put(currFile, new ArrayList<StyleProblem>());
}
 
Example #9
Source File: AssertionsAuditListener.java    From nohttp with Apache License 2.0 5 votes vote down vote up
@Override
public void addError(AuditEvent event) {
	recordLevel(event);
	if (event.getSeverityLevel() != SeverityLevel.IGNORE) {
		recordMessage(FORMATTER.format(event));
	}
}
 
Example #10
Source File: VerboseListener.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Prints event information to standard output.
 * @param aEvt the event to print.
 */
private void printEvent(AuditEvent aEvt)
{
    mWriter.println("Logging error -"
        + " file: '" + aEvt.getFileName() + "'"
        + " line: " + aEvt.getLine()
        + " column: " + aEvt.getColumn()
        + " severity: " + aEvt.getSeverityLevel()
        + " message: " + aEvt.getMessage()
        + " source: " + aEvt.getSourceName());
}
 
Example #11
Source File: CommonsLoggingListener.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void auditStarted(AuditEvent aEvt)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(Checker.class);
        log.info("Audit started.");
    }
}
 
Example #12
Source File: AssertionsAuditListener.java    From nohttp with Apache License 2.0 5 votes vote down vote up
@Override
public void auditFinished(AuditEvent event) {
	recordLevel(event);
	recordLocalizedMessage(DefaultLogger.AUDIT_FINISHED_MESSAGE);
	recordMessage(this.severityCounts.toString());
	int errors = this.severityCounts.getOrDefault(SeverityLevel.ERROR, 0);
	recordMessage(errors + (errors == 1 ? " error" : " errors"));
	System.out.println(this.filenames);
	System.out.println(this.message);
	this.checks.forEach(this::runCheck);
}
 
Example #13
Source File: CommonsLoggingListener.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void auditFinished(AuditEvent aEvt)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(Checker.class);
        log.info("Audit finished.");
    }
}
 
Example #14
Source File: DiffLineFilterTest.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testAcceptWithEmptyLineSeparator() {
    String fileName = "test";
    int lineNum = 10;
    int beginB = 5;
    int endB = 9;

    LocalizedMessage message = PowerMockito.mock(LocalizedMessage.class);
    PowerMockito.doReturn(EmptyLineSeparatorCheck.class.getName()).when(message).getSourceName();

    AuditEvent event = PowerMockito.mock(AuditEvent.class);
    PowerMockito.doReturn(fileName).when(event).getFileName();
    PowerMockito.doReturn(lineNum).when(event).getLine();
    PowerMockito.doReturn(message).when(event).getLocalizedMessage();

    Edit edit = PowerMockito.mock(Edit.class);
    PowerMockito.doReturn(beginB).when(edit).getBeginB();
    PowerMockito.doReturn(endB).when(edit).getEndB();

    DiffEntryWrapper wrapper = PowerMockito.mock(DiffEntryWrapper.class);
    PowerMockito.doReturn(fileName).when(wrapper).getAbsoluteNewPath();
    PowerMockito.doReturn(Arrays.asList(edit)).when(wrapper).getEditList();

    DiffLineFilter filter = new DiffLineFilter(Arrays.asList(wrapper));

    Assert.assertTrue(filter.accept(event));
}
 
Example #15
Source File: CoderadarAuditListener.java    From coderadar with MIT License 5 votes vote down vote up
@Override
public void addError(AuditEvent evt) {
  if (evt.getSeverityLevel() != SeverityLevel.IGNORE) {
    Metric metric = new Metric("checkstyle:" + evt.getSourceName());
    Finding finding =
        new Finding(
            evt.getLine(), evt.getLine(), evt.getColumn(), evt.getColumn(), evt.getMessage());
    Long metricCount = metricCountExtractor.extractMetricCount(evt);
    metrics.addFinding(metric, finding, metricCount);
  }
}
 
Example #16
Source File: Auditor.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void fileFinished(AuditEvent event) {
  // update monitor according to the monitor interval
  if (mMonitorCounter == MONITOR_INTERVAL) {
    mMonitor.worked(MONITOR_INTERVAL);
    mMonitorCounter = 0;
  }

  disconnectFileBuffer(mResource);
  mDocument = null;
}
 
Example #17
Source File: MailLogger.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void addError(AuditEvent aEvt)
{
    if (SeverityLevel.ERROR.equals(aEvt.getSeverityLevel())) {
        mLogger.addError(aEvt);
        mErrors++;
    }
}
 
Example #18
Source File: CheckstyleAuditListener.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
@VisibleForTesting
static int getLineId(AuditEvent event) {
    int result = 1;
    try {
        final int eventLine = event.getLine();
        if (eventLine > 0) {
            result = eventLine;
        }
    }
    catch (Exception ex) {
        LOG.warn("AuditEvent is created incorrectly. Exception happen during getLine()", ex);
    }
    return result;
}
 
Example #19
Source File: VerboseListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void addError(AuditEvent aEvt)
{
    printEvent(aEvt);
    if (SeverityLevel.ERROR.equals(aEvt.getSeverityLevel())) {
        mErrors++;
        mTotalErrors++;
    }
}
 
Example #20
Source File: Auditor.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String getMessage(AuditEvent error) {

      String moduleId = error.getModuleId();

      if (moduleId == null) {
        RuleMetadata metaData = MetadataFactory.getRuleMetadata(error.getSourceName());
        if (metaData != null) {
          moduleId = metaData.getInternalName();
        }
      }

      final String message = error.getMessage();

      StringBuffer prefix = new StringBuffer();
      if (mAddRuleName) {
        prefix.append(getRuleName(error));
      }
      if (mAddModuleId && error.getModuleId() != null) {
        if (prefix.length() > 0) {
          prefix.append(" - "); //$NON-NLS-1$
        }
        prefix.append(error.getModuleId());
      }

      StringBuffer buf = new StringBuffer();
      if (prefix.length() > 0) {
        buf.append(prefix).append(": "); //$NON-NLS-1$
      }
      buf.append(message);

      return buf.toString();
    }
 
Example #21
Source File: Auditor.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String getRuleName(AuditEvent error) {
  RuleMetadata metaData = MetadataFactory.getRuleMetadata(error.getSourceName());
  if (metaData == null) {
    return Messages.Auditor_txtUnknownModule;
  }
  return metaData.getRuleName();
}
 
Example #22
Source File: CheckerListener.java    From vscode-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void addError(AuditEvent error) {
    final SeverityLevel severity = error.getSeverityLevel();
    if (severity.equals(SeverityLevel.IGNORE)) {
        return;
    }
    fileErrors.get(error.getFileName()).add(new CheckResult(
        error.getLine(),
        error.getColumn(),
        error.getMessage(),
        severity.toString().toLowerCase(),
        error.getSourceName().substring(error.getSourceName().lastIndexOf('.') + 1)));
}
 
Example #23
Source File: CheckstyleAuditListener.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void initResource(AuditEvent event) {
    if (currentResource == null) {
        final String absoluteFilename = event.getFileName();
        currentResource = fileSystem.inputFile(fileSystem.predicates().hasAbsolutePath(
                absoluteFilename));
    }
}
 
Example #24
Source File: CommonsLoggingListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void addException(AuditEvent aEvt, Throwable aThrowable)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(aEvt.getSourceName());
        log.error("Error auditing " + aEvt.getFileName(), aThrowable);
    }
}
 
Example #25
Source File: CommonsLoggingListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void addError(AuditEvent aEvt)
{
    final SeverityLevel severityLevel = aEvt.getSeverityLevel();
    if (mInitialized && !SeverityLevel.IGNORE.equals(severityLevel)) {
        final Log log = mLogFactory.getInstance(aEvt.getSourceName());

        final String fileName = aEvt.getFileName();
        final String message = aEvt.getMessage();

        // avoid StringBuffer.expandCapacity
        final int bufLen = message.length() + BUFFER_CUSHION;
        final StringBuffer sb = new StringBuffer(bufLen);

        sb.append("Line: ").append(aEvt.getLine());
        if (aEvt.getColumn() > 0) {
            sb.append(" Column: ").append(aEvt.getColumn());
        }
        sb.append(" Message: ").append(message);

        if (aEvt.getSeverityLevel().equals(SeverityLevel.WARNING)) {
            log.warn(sb.toString());
        }
        else if (aEvt.getSeverityLevel().equals(SeverityLevel.INFO)) {
            log.info(sb.toString());
        }
        else {
            log.error(sb.toString());
        }
    }
}
 
Example #26
Source File: CommonsLoggingListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void fileFinished(AuditEvent aEvt)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(Checker.class);
        log.info("File \"" + aEvt.getFileName() + "\" finished.");
    }
}
 
Example #27
Source File: CommonsLoggingListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void fileStarted(AuditEvent aEvt)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(Checker.class);
        log.info("File \"" + aEvt.getFileName() + "\" started.");
    }
}
 
Example #28
Source File: CommonsLoggingListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void auditFinished(AuditEvent aEvt)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(Checker.class);
        log.info("Audit finished.");
    }
}
 
Example #29
Source File: CheckstyleAuditListener.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void addError(AuditEvent event) {
    final String ruleKey = getRuleKey(event);

    if (Objects.nonNull(ruleKey)) {
        final String message = getMessage(event);
        // In Checkstyle 5.5 exceptions are reported as an events from
        // TreeWalker
        if ("com.puppycrawl.tools.checkstyle.TreeWalker".equals(ruleKey)) {
            LOG.warn("{} : {}", event.getFileName(), message);
        }

        initResource(event);

        final NewIssue issue = context.newIssue();
        final ActiveRule rule = ruleFinder.find(
                RuleKey.of(CheckstyleConstants.REPOSITORY_KEY, ruleKey));
        if (Objects.nonNull(issue) && Objects.nonNull(rule)) {
            final NewIssueLocation location = issue.newLocation()
                    .on(currentResource)
                    .at(currentResource.selectLine(getLineId(event)))
                    .message(message);
            issue.forRule(rule.ruleKey())
                    .at(location)
                    .save();
        }
    }
}
 
Example #30
Source File: VerboseListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Prints event information to standard output.
 * @param aEvt the event to print.
 */
private void printEvent(AuditEvent aEvt)
{
    mWriter.println("Logging error -"
        + " file: '" + aEvt.getFileName() + "'"
        + " line: " + aEvt.getLine()
        + " column: " + aEvt.getColumn()
        + " severity: " + aEvt.getSeverityLevel()
        + " message: " + aEvt.getMessage()
        + " source: " + aEvt.getSourceName());
}