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

The following examples show how to use com.puppycrawl.tools.checkstyle.api.LocalizedMessage. 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: Main.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Loads properties from a File.
 * @param file
 *        the properties file
 * @return the properties in file
 * @throws CheckstyleException
 *         when could not load properties file
 */
private static Properties loadProperties(File file)
        throws CheckstyleException {
    final Properties properties = new Properties();

    try (InputStream stream = Files.newInputStream(file.toPath())) {
        properties.load(stream);
    }
    catch (final IOException ex) {
        final LocalizedMessage loadPropertiesExceptionMessage = new LocalizedMessage(1,
                Definitions.CHECKSTYLE_BUNDLE, LOAD_PROPERTIES_EXCEPTION,
                new String[] {file.getAbsolutePath()}, null, Main.class, null);
        throw new CheckstyleException(loadPropertiesExceptionMessage.getMessage(), ex);
    }

    return properties;
}
 
Example #2
Source File: AbstractCheckVisitor.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Log an error message.
 *
 * @param aLine the line number where the error was found
 * @param aKey the message that describes the error
 * @param aArgs the details of the message
 *
 * @see java.text.MessageFormat
 */
private final void log(String fileName, int aLine, String aKey, Object aArgs[])
{
    LocalizedMessages localizedMessages = (LocalizedMessages) mMessageMap.get(fileName);
    if (localizedMessages == null) {
        localizedMessages = new LocalizedMessages();
        mMessageMap.put(fileName, localizedMessages);
    }
    localizedMessages.add(
        new LocalizedMessage(
            aLine,
            getMessageBundle(),
            aKey,
            aArgs,
            getSeverityLevel(),
            this.getClass()));
}
 
Example #3
Source File: AbstractCheckVisitor.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Log an error message.
 *
 * @param aLine the line number where the error was found
 * @param aKey the message that describes the error
 * @param aArgs the details of the message
 *
 * @see java.text.MessageFormat
 */
private final void log(String fileName, int aLine, String aKey, Object aArgs[])
{
    LocalizedMessages localizedMessages = (LocalizedMessages) mMessageMap.get(fileName);
    if (localizedMessages == null) {
        localizedMessages = new LocalizedMessages();
        mMessageMap.put(fileName, localizedMessages);
    }
    localizedMessages.add(
        new LocalizedMessage(
            aLine,
            getMessageBundle(),
            aKey,
            aArgs,
            getSeverityLevel(),
            this.getClass()));
}
 
Example #4
Source File: MetricCountExtractor.java    From coderadar with MIT License 5 votes vote down vote up
private Long extractLongArgument(AuditEvent event, int position)
    throws NoSuchFieldException, IllegalAccessException {
  Field argsField = LocalizedMessage.class.getDeclaredField("args");
  argsField.setAccessible(true);
  Object[] args = (Object[]) argsField.get(event.getLocalizedMessage());
  Number count = (Number) args[position];
  return count.longValue();
}
 
Example #5
Source File: ClassFileSetCheck.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Notify all listeners about the errors in a file.
 * Calls <code>MessageDispatcher.fireErrors()</code> with
 * all logged errors and than clears errors' list.
 */
private void fireErrors()
{
    Set keys = mMessageMap.keySet();
    Iterator iter = keys.iterator();
    while (iter.hasNext()) {
        String key = (String) iter.next();
        getMessageDispatcher().fireFileStarted(key);
        LocalizedMessages localizedMessages = (LocalizedMessages) mMessageMap.get(key);
        final LocalizedMessage[] errors = localizedMessages.getMessages();
        localizedMessages.reset();
        getMessageDispatcher().fireErrors(key, errors);
        getMessageDispatcher().fireFileFinished(key);
    }
}
 
Example #6
Source File: ClassFileSetCheck.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Notify all listeners about the errors in a file.
 * Calls <code>MessageDispatcher.fireErrors()</code> with
 * all logged errors and than clears errors' list.
 */
private void fireErrors()
{
    Set keys = mMessageMap.keySet();
    Iterator iter = keys.iterator();
    while (iter.hasNext()) {
        String key = (String) iter.next();
        getMessageDispatcher().fireFileStarted(key);
        LocalizedMessages localizedMessages = (LocalizedMessages) mMessageMap.get(key);
        final LocalizedMessage[] errors = localizedMessages.getMessages();
        localizedMessages.reset();
        getMessageDispatcher().fireErrors(key, errors);
        getMessageDispatcher().fireFileFinished(key);
    }
}
 
Example #7
Source File: CheckstyleAuditListenerTest.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void addErrorOnTreeWalkerRule() {
    final AuditEvent treeWalkerEvent = new AuditEvent(
            this,
            file.getAbsolutePath(),
            new LocalizedMessage(42, "", "", null, "",
                    TreeWalker.class, "msg"));

    when(context.newIssue()).thenReturn(null);
    addErrorToListener(treeWalkerEvent);
    verify(context, times(1)).newIssue();
}
 
Example #8
Source File: CheckstyleAuditListenerTest.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void addErrorTestForLine(final int pLineNo) {
    final ActiveRule rule = setupRule("repo", "key");

    final NewIssue newIssue = mock(NewIssue.class);
    final NewIssueLocation newLocation = mock(NewIssueLocation.class);
    when(context.newIssue()).thenReturn(newIssue);
    when(newIssue.newLocation()).thenReturn(newLocation);
    when(newIssue.forRule(rule.ruleKey())).thenReturn(newIssue);
    when(newIssue.at(newLocation)).thenReturn(newIssue);
    when(newLocation.on(any(InputComponent.class))).thenReturn(newLocation);
    when(newLocation.at(any(TextRange.class))).thenReturn(newLocation);
    when(newLocation.message(anyString())).thenReturn(newLocation);

    when(inputFile.selectLine(anyInt())).thenReturn(new DefaultTextRange(
        new DefaultTextPointer(1, 1), new DefaultTextPointer(1, 2)));

    final AuditEvent eventAdded = new AuditEvent(this, file.getAbsolutePath(),
        new LocalizedMessage(pLineNo, "", "", null, "", CheckstyleAuditListenerTest.class,
            "msg"));
    addErrorToListener(eventAdded);

    verify(newIssue, times(1)).save();
    verify(newIssue, times(1)).forRule(rule.ruleKey());
    verify(newIssue, times(1)).at(newLocation);
    verify(newIssue, times(1)).newLocation();
    verify(newLocation, times(1)).on(any());
    verify(newLocation, times(1)).at(any());
    verify(newLocation, times(1)).message(any());
}
 
Example #9
Source File: RequiresOuterThisFilter.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private static Field getArgsField() {
	try {
		Field field = LocalizedMessage.class.getDeclaredField("args");
		field.setAccessible(true);
		return field;
	}
	catch (Exception ex) {
		return null;
	}
}
 
Example #10
Source File: RequiresOuterThisFilter.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private Object[] getArgs(LocalizedMessage message) {
	if (ARGS_FIELD == null) {
		throw new IllegalStateException("Unable to extract message args");
	}
	try {
		return (Object[]) ARGS_FIELD.get(message);
	}
	catch (Exception ex) {
		return null;
	}
}
 
Example #11
Source File: RequiresOuterThisFilter.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
@Override
public boolean accept(TreeWalkerAuditEvent event) {
	LocalizedMessage message = event.getLocalizedMessage();
	if ("require.this.variable".equals(message.getKey())) {
		Object[] args = getArgs(message);
		String prefex = (args.length > 1 ? Objects.toString(args[1]) : null);
		if (prefex != null && prefex.length() > 0) {
			return false;
		}
	}
	return true;
}
 
Example #12
Source File: SpringChecks.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
@Override
protected void processFiltered(File file, FileText fileText) throws CheckstyleException {
	SortedSet<LocalizedMessage> messages = new TreeSet<>();
	for (FileSetCheck check : this.checks) {
		messages.addAll(check.process(file, fileText));
	}
	addMessages(messages);
}
 
Example #13
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 #14
Source File: AssertionsAuditListener.java    From spring-javaformat with Apache License 2.0 4 votes vote down vote up
private void recordLocalizedMessage(String message, String... args) {
	recordMessage(new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, message, args, null,
			LocalizedMessage.class, null).getMessage());
}
 
Example #15
Source File: CheckFilter.java    From spring-javaformat with Apache License 2.0 4 votes vote down vote up
@Override
public SortedSet<LocalizedMessage> getMessages() {
	return this.check.getMessages();
}
 
Example #16
Source File: AssertionsAuditListener.java    From nohttp with Apache License 2.0 4 votes vote down vote up
private void recordLocalizedMessage(String message, String... args) {
	recordMessage(new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, message,
			args, null, LocalizedMessage.class, null).getMessage());
}
 
Example #17
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Loops over the files specified checking them for errors. The exit code
 * is the number of errors found in all the files.
 * @param args the command line arguments.
 * @throws IOException if there is a problem with files access
 * @noinspection CallToPrintStackTrace, CallToSystemExit
 **/
public static void main(String... args) throws IOException {
    int errorCounter = 0;
    boolean cliViolations = false;
    // provide proper exit code based on results.
    final int exitWithCliViolation = -1;
    int exitStatus = 0;

    try {
        //parse CLI arguments
        final CommandLine commandLine = parseCli(args);

        // show version and exit if it is requested
        if (commandLine.hasOption(OPTION_V_NAME)) {
            System.out.println("Checkstyle version: "
                    + Main.class.getPackage().getImplementationVersion());
            exitStatus = 0;
        }
        else {
            List<File> filesToProcess = Collections.emptyList();

            if (commandLine.hasOption(OPTION_GIT_DIR_NAME)) {
                filesToProcess = getGitDiffFilesToProcess(getExclusions(commandLine), commandLine);
                if (CollectionUtils.isEmpty(filesToProcess)) {
                    System.out.println("There is no file need to check");
                    return;
                }
            } else {
                filesToProcess = getFilesToProcess(getExclusions(commandLine),
                        commandLine.getArgs());
            }

            // return error if something is wrong in arguments
            final List<String> messages = validateCli(commandLine, filesToProcess);
            cliViolations = !messages.isEmpty();
            if (cliViolations) {
                exitStatus = exitWithCliViolation;
                errorCounter = 1;
                messages.forEach(System.out::println);
            }
            else {
                errorCounter = runCli(commandLine, filesToProcess);
                exitStatus = errorCounter;
            }
        }
    }
    catch (ParseException pex) {
        // something wrong with arguments - print error and manual
        cliViolations = true;
        exitStatus = exitWithCliViolation;
        errorCounter = 1;
        System.out.println(pex.getMessage());
        printUsage();
    }
    catch (CheckstyleException ex) {
        exitStatus = EXIT_WITH_CHECKSTYLE_EXCEPTION_CODE;
        errorCounter = 1;
        ex.printStackTrace();
    }
    finally {
        // return exit code base on validation of Checker
        // two ifs exist till https://github.com/hcoles/pitest/issues/377
        if (errorCounter != 0) {
            if (!cliViolations) {
                final LocalizedMessage errorCounterMessage = new LocalizedMessage(1,
                        Definitions.CHECKSTYLE_BUNDLE, ERROR_COUNTER,
                        new String[] {String.valueOf(errorCounter)}, null, Main.class, null);
                System.out.println(errorCounterMessage.getMessage());
            }
        }
        if (exitStatus != 0) {
            System.exit(exitStatus);
        }
    }
}