Search in sources :

Example 11 with CheckstyleException

use of com.puppycrawl.tools.checkstyle.api.CheckstyleException in project checkstyle by checkstyle.

the class XdocsPagesTest method validateCheckstyleXml.

private static void validateCheckstyleXml(String fileName, String code, String unserializedSource) throws IOException, CheckstyleException {
    // can't process non-existent examples, or out of context snippets
    if (!code.contains("com.mycompany") && !code.contains("checkstyle-packages") && !code.contains("MethodLimit") && !code.contains("<suppress ") && !code.contains("<import-control ") && !unserializedSource.startsWith("<property ") && !unserializedSource.startsWith("<taskdef ")) {
        // validate checkstyle structure and contents
        try {
            final Properties properties = new Properties();
            properties.setProperty("checkstyle.header.file", new File("config/java.header").getCanonicalPath());
            final PropertiesExpander expander = new PropertiesExpander(properties);
            final Configuration config = ConfigurationLoader.loadConfiguration(new InputSource(new StringReader(code)), expander, false);
            final Checker checker = new Checker();
            try {
                final ClassLoader moduleClassLoader = Checker.class.getClassLoader();
                checker.setModuleClassLoader(moduleClassLoader);
                checker.configure(config);
            } finally {
                checker.destroy();
            }
        } catch (CheckstyleException ex) {
            throw new CheckstyleException(fileName + " has invalid Checkstyle xml (" + ex.getMessage() + "): " + unserializedSource, ex);
        }
    }
}
Also used : InputSource(org.xml.sax.InputSource) Checker(com.puppycrawl.tools.checkstyle.Checker) Configuration(com.puppycrawl.tools.checkstyle.api.Configuration) PropertiesExpander(com.puppycrawl.tools.checkstyle.PropertiesExpander) StringReader(java.io.StringReader) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) Properties(java.util.Properties) File(java.io.File)

Example 12 with CheckstyleException

use of com.puppycrawl.tools.checkstyle.api.CheckstyleException in project checkstyle by checkstyle.

the class CommonUtilsTest method testLoadSuppressionsUriSyntaxException.

@Test
@PrepareForTest({ CommonUtils.class, CommonUtilsTest.class })
@SuppressWarnings("unchecked")
public void testLoadSuppressionsUriSyntaxException() throws Exception {
    final URL configUrl = mock(URL.class);
    when(configUrl.toURI()).thenThrow(URISyntaxException.class);
    mockStatic(CommonUtils.class, Mockito.CALLS_REAL_METHODS);
    final String fileName = "suppressions_none.xml";
    when(CommonUtils.class.getResource(fileName)).thenReturn(configUrl);
    try {
        CommonUtils.getUriByFilename(fileName);
        fail("Exception is expected");
    } catch (CheckstyleException ex) {
        assertTrue(ex.getCause() instanceof URISyntaxException);
        assertEquals("Unable to find: " + fileName, ex.getMessage());
    }
}
Also used : CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) URISyntaxException(java.net.URISyntaxException) URL(java.net.URL) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 13 with CheckstyleException

use of com.puppycrawl.tools.checkstyle.api.CheckstyleException in project checkstyle by checkstyle.

the class PackageNamesLoader method getPackageNames.

/**
     * Returns the set of package names, compiled from all
     * checkstyle_packages.xml files found on the given class loaders
     * classpath.
     * @param classLoader the class loader for loading the
     *          checkstyle_packages.xml files.
     * @return the set of package names.
     * @throws CheckstyleException if an error occurs.
     */
public static Set<String> getPackageNames(ClassLoader classLoader) throws CheckstyleException {
    final Set<String> result;
    try {
        //create the loader outside the loop to prevent PackageObjectFactory
        //being created anew for each file
        final PackageNamesLoader namesLoader = new PackageNamesLoader();
        final Enumeration<URL> packageFiles = classLoader.getResources(CHECKSTYLE_PACKAGES);
        while (packageFiles.hasMoreElements()) {
            final URL packageFile = packageFiles.nextElement();
            InputStream stream = null;
            try {
                stream = new BufferedInputStream(packageFile.openStream());
                final InputSource source = new InputSource(stream);
                namesLoader.parseInputSource(source);
            } catch (IOException ex) {
                throw new CheckstyleException("unable to open " + packageFile, ex);
            } finally {
                Closeables.closeQuietly(stream);
            }
        }
        result = namesLoader.packageNames;
    } catch (IOException ex) {
        throw new CheckstyleException("unable to get package file resources", ex);
    } catch (ParserConfigurationException | SAXException ex) {
        throw new CheckstyleException("unable to open one of package files", ex);
    }
    return result;
}
Also used : InputSource(org.xml.sax.InputSource) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) IOException(java.io.IOException) URL(java.net.URL) SAXException(org.xml.sax.SAXException) BufferedInputStream(java.io.BufferedInputStream) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 14 with CheckstyleException

use of com.puppycrawl.tools.checkstyle.api.CheckstyleException in project checkstyle by checkstyle.

the class PackageObjectFactory method createObject.

/**
     * Creates a new instance of a named class.
     * @param className the name of the class to instantiate.
     * @return the {@code Object} created by loader or null.
     * @throws CheckstyleException if the class fails to instantiate.
     */
private Object createObject(String className) throws CheckstyleException {
    Class<?> clazz = null;
    try {
        clazz = Class.forName(className, true, moduleClassLoader);
    } catch (final ReflectiveOperationException | NoClassDefFoundError ignored) {
    // keep looking, ignoring exception
    }
    Object instance = null;
    if (clazz != null) {
        try {
            final Constructor<?> declaredConstructor = clazz.getDeclaredConstructor();
            declaredConstructor.setAccessible(true);
            instance = declaredConstructor.newInstance();
        } catch (final ReflectiveOperationException ex) {
            throw new CheckstyleException("Unable to instatiate " + className, ex);
        }
    }
    return instance;
}
Also used : CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException)

Example 15 with CheckstyleException

use of com.puppycrawl.tools.checkstyle.api.CheckstyleException in project checkstyle by checkstyle.

the class PackageObjectFactory method createModule.

/**
     * Creates a new instance of a class from a given name, or that name
     * concatenated with &quot;Check&quot;. If the name is
     * a class name, creates an instance of the named class. Otherwise, creates
     * an instance of a class name obtained by concatenating the given name
     * to a package name from a given list of package names.
     * @param name the name of a class.
     * @return the {@code Object} created by loader.
     * @throws CheckstyleException if an error occurs.
     */
@Override
public Object createModule(String name) throws CheckstyleException {
    Object instance = createObjectFromMap(name);
    if (instance == null) {
        instance = createObjectWithIgnoringProblems(name, getAllPossibleNames(name));
    }
    if (instance == null) {
        final String nameCheck = name + CHECK_SUFFIX;
        instance = createObjectWithIgnoringProblems(nameCheck, getAllPossibleNames(nameCheck));
        if (instance == null) {
            final String attemptedNames = joinPackageNamesWithClassName(name, packages) + STRING_SEPARATOR + nameCheck + STRING_SEPARATOR + joinPackageNamesWithClassName(nameCheck, packages);
            final LocalizedMessage exceptionMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, UNABLE_TO_INSTANTIATE_EXCEPTION_MESSAGE, new String[] { name, attemptedNames }, null, getClass(), null);
            throw new CheckstyleException(exceptionMessage.getMessage());
        }
    }
    return instance;
}
Also used : CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) LocalizedMessage(com.puppycrawl.tools.checkstyle.api.LocalizedMessage)

Aggregations

CheckstyleException (com.puppycrawl.tools.checkstyle.api.CheckstyleException)78 Test (org.junit.Test)46 DefaultConfiguration (com.puppycrawl.tools.checkstyle.DefaultConfiguration)33 File (java.io.File)15 IOException (java.io.IOException)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 Configuration (com.puppycrawl.tools.checkstyle.api.Configuration)9 Properties (java.util.Properties)8 URL (java.net.URL)6 SAXException (org.xml.sax.SAXException)5 PropertiesExpander (com.puppycrawl.tools.checkstyle.PropertiesExpander)4 URI (java.net.URI)4 Checker (com.puppycrawl.tools.checkstyle.Checker)3 DetailAST (com.puppycrawl.tools.checkstyle.api.DetailAST)3 BufferedInputStream (java.io.BufferedInputStream)3 FileInputStream (java.io.FileInputStream)3 Method (java.lang.reflect.Method)3 MalformedURLException (java.net.MalformedURLException)3 ArrayList (java.util.ArrayList)3 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)3