@Override public String getAttribute(String attributeName) throws CheckstyleException { if (!attributeMap.containsKey(attributeName)) { throw new CheckstyleException( "missing key '" + attributeName + "' in " + name); } return attributeMap.get(attributeName); }
/** * Retrieves the folder path from the given {@code file}. * * @param file Input file to examine. * @return The folder path. * @throws CheckstyleException if there is an error getting the canonical * path of the {@code file}. */ private static String getFolderPath(File file) throws CheckstyleException { try { return file.getCanonicalFile().getParent(); } catch (IOException ex) { throw new CheckstyleException("unable to create canonical path names for " + file.getAbsolutePath(), ex); } }
/** * Loads the import control file from a file. * @param uri the uri of the file to load. * @return the root {@link PkgImportControl} object. * @throws CheckstyleException if an error occurs. */ public static PkgImportControl load(URI uri) throws CheckstyleException { try (InputStream inputStream = uri.toURL().openStream()) { final InputSource source = new InputSource(inputStream); return load(source, uri); } catch (MalformedURLException ex) { throw new CheckstyleException("syntax error in url " + uri, ex); } catch (IOException ex) { throw new CheckstyleException("unable to find " + uri, ex); } }
/** * Reads the file provided and parses it with package names loader. * @param packageFile file from package * @param namesLoader package names loader * @throws SAXException if an error while parsing occurs * @throws CheckstyleException if unable to open file */ private static void processFile(URL packageFile, PackageNamesLoader namesLoader) throws SAXException, CheckstyleException { try (InputStream 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); } }
/** * 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) { // ignore the 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 instantiate " + className, ex); } } return instance; }
/** * Loads the content of external resource. * @param location external resource location. * @return array of bytes which represents the content of external resource in binary form. * @throws CheckstyleException if error while loading occurs. */ private static byte[] loadExternalResource(String location) throws CheckstyleException { final byte[] content; final URI uri = CommonUtil.getUriByFilename(location); try { content = ByteStreams.toByteArray(new BufferedInputStream(uri.toURL().openStream())); } catch (IOException ex) { throw new CheckstyleException("Unable to load external resource file " + location, ex); } return content; }
/** * Load the header from a file. * @throws CheckstyleException if the file cannot be loaded */ private void loadHeaderFile() throws CheckstyleException { checkHeaderNotInitialized(); try (Reader headerReader = new InputStreamReader(new BufferedInputStream( headerFile.toURL().openStream()), charset)) { loadHeader(headerReader); } catch (final IOException ex) { throw new CheckstyleException( "unable to load header file " + headerFile, ex); } }
/** * Validates that check's required tokens are subset of default tokens. * @param check to validate * @throws CheckstyleException when validation of default tokens fails */ private static void validateDefaultTokens(AbstractCheck check) throws CheckstyleException { final int[] defaultTokens = check.getDefaultTokens(); Arrays.sort(defaultTokens); for (final int token : check.getRequiredTokens()) { if (Arrays.binarySearch(defaultTokens, token) < 0) { final String message = String.format(Locale.ROOT, "Token \"%s\" from required " + "tokens was not found in default tokens list in check %s", token, check.getClass().getName()); throw new CheckstyleException(message); } } }
/** * Register a check for a specified token name. * @param token the name of the token * @param check the check to register * @throws CheckstyleException if Check is misconfigured */ private void registerCheck(String token, AbstractCheck check) throws CheckstyleException { if (check.isCommentNodesRequired()) { tokenToCommentChecks.computeIfAbsent(token, empty -> new HashSet<>()).add(check); } else if (TokenUtil.isCommentType(token)) { final String message = String.format(Locale.ROOT, "Check '%s' waits for comment type " + "token ('%s') and should override 'isCommentNodesRequired()' " + "method to return 'true'", check.getClass().getName(), token); throw new CheckstyleException(message); } else { tokenToOrdinaryChecks.computeIfAbsent(token, empty -> new HashSet<>()).add(check); } }
/** * 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; }
/** * Set the header file to check against. * @param uri the uri of the header to load. * @throws CheckstyleException if fileName is empty. */ public void setHeaderFile(URI uri) throws CheckstyleException { if (uri == null) { throw new CheckstyleException( "property 'headerFile' is missing or invalid in module " + getConfiguration().getName()); } headerFile = uri; }
@Override protected void processFiltered(File file, FileText fileText) throws CheckstyleException { // Check if already processed directory final File dir; try { dir = file.getCanonicalFile().getParentFile(); } catch (IOException ex) { throw new CheckstyleException( "Exception while getting canonical path to file " + file.getPath(), ex); } final boolean isDirChecked = !directoriesChecked.add(dir); if (!isDirChecked) { // Check for the preferred file. final File packageInfo = new File(dir, "package-info.java"); final File packageHtml = new File(dir, "package.html"); if (packageInfo.exists()) { if (packageHtml.exists()) { log(1, MSG_LEGACY_PACKAGE_HTML); } } else if (!allowLegacy || !packageHtml.exists()) { log(1, MSG_PACKAGE_INFO); } } }
/** * Loads the import control file from a {@link InputSource}. * @param source the source to load from. * @param uri uri of the source being loaded. * @return the root {@link PkgImportControl} object. * @throws CheckstyleException if an error occurs. */ private static PkgImportControl load(InputSource source, URI uri) throws CheckstyleException { try { final ImportControlLoader loader = new ImportControlLoader(); loader.parseInputSource(source); return loader.getRoot(); } catch (ParserConfigurationException | SAXException ex) { throw new CheckstyleException("unable to parse " + uri + " - " + ex.getMessage(), ex); } catch (IOException ex) { throw new CheckstyleException("unable to read " + uri, ex); } }
/** * Create Object from optional full module names. * In most case, there should be only one element in {@code fullModuleName}, otherwise * an exception would be thrown. * @param name name of module * @param fullModuleNames the supplied full module names set * @return instance of module if there is only one element in {@code fullModuleName} * @throws CheckstyleException if the class fails to instantiate or there are more than one * element in {@code fullModuleName} */ private Object createObjectFromFullModuleNames(String name, Set<String> fullModuleNames) throws CheckstyleException { final Object returnValue; if (fullModuleNames.size() == 1) { returnValue = createObject(fullModuleNames.iterator().next()); } else { final String optionalNames = fullModuleNames.stream() .sorted() .collect(Collectors.joining(STRING_SEPARATOR)); final LocalizedMessage exceptionMessage = new LocalizedMessage(1, Definitions.CHECKSTYLE_BUNDLE, AMBIGUOUS_MODULE_NAME_EXCEPTION_MESSAGE, new String[] {name, optionalNames}, null, getClass(), null); throw new CheckstyleException(exceptionMessage.getMessage()); } return returnValue; }
/** * Creates the .properties file from a .java file. * @param options the user-specified options * @throws CheckstyleException if a javadoc comment can not be parsed */ private static void writePropertiesFile(CliOptions options) throws CheckstyleException { try (PrintWriter writer = new PrintWriter(options.outputFile, StandardCharsets.UTF_8.name())) { final DetailAST top = JavaParser.parseFile(options.inputFile, JavaParser.Options.WITH_COMMENTS); final DetailAST objBlock = getClassBody(top); if (objBlock != null) { iteratePublicStaticIntFields(objBlock, writer::println); } } catch (IOException ex) { throw new CheckstyleException("Failed to write javadoc properties of '" + options.inputFile + "' to '" + options.outputFile + "'", ex); } }
/** * Called by configure() for every child of this component's Configuration. * <p> * The default implementation throws {@link CheckstyleException} if * {@code childConf} is {@code null} because it doesn't support children. It * must be overridden to validate and support children that are wanted. * </p> * * @param childConf a child of this component's Configuration * @throws CheckstyleException if there is a configuration error. * @see Configuration#getChildren */ protected void setupChild(Configuration childConf) throws CheckstyleException { if (childConf != null) { throw new CheckstyleException(childConf.getName() + " is not allowed as a child in " + configuration.getName() + ". Please review 'Parent Module' section " + "for this Check in web documentation if Check is standard."); } }
private static void examineCheckSection(ModuleFactory moduleFactory, String fileName, String sectionName, Node section) throws Exception { final Object instance; try { instance = moduleFactory.createModule(sectionName); } catch (CheckstyleException ex) { throw new CheckstyleException(fileName + " couldn't find class: " + sectionName, ex); } CHECK_TEXT.clear(); CHECK_PROPERTIES.clear(); CHECK_PROPERTY_DOC.clear(); checkName = sectionName; examineCheckSectionChildren(section); final List<File> files = new ArrayList<>(); files.add(new File("src/main/java/" + instance.getClass().getName().replace(".", "/") + ".java")); checker.process(files); }
/** * {@inheritDoc} Creates child module. * @noinspection ChainOfInstanceofChecks */ @Override public void setupChild(Configuration childConf) throws CheckstyleException { final String name = childConf.getName(); final Object module = moduleFactory.createModule(name); if (module instanceof AutomaticBean) { final AutomaticBean bean = (AutomaticBean) module; bean.contextualize(childContext); bean.configure(childConf); } if (module instanceof AbstractCheck) { final AbstractCheck check = (AbstractCheck) module; check.init(); registerCheck(check); } else if (module instanceof TreeWalkerFilter) { final TreeWalkerFilter filter = (TreeWalkerFilter) module; filters.add(filter); } else { throw new CheckstyleException( "TreeWalker is not allowed as a parent of " + name + " Please review 'Parent Module' section for this Check in web" + " documentation if Check is standard."); } }
/** * Static helper method to parses a Java source file. * @param contents contains the contents of the file * @return the root of the AST * @throws CheckstyleException if the contents is not a valid Java source */ public static DetailAST parse(FileContents contents) throws CheckstyleException { final String fullText = contents.getText().getFullText().toString(); final Reader reader = new StringReader(fullText); final GeneratedJavaLexer lexer = new GeneratedJavaLexer(reader); lexer.setCommentListener(contents); lexer.setTokenObjectClass("antlr.CommonHiddenStreamToken"); final TokenStreamHiddenTokenFilter filter = new TokenStreamHiddenTokenFilter(lexer); filter.hide(TokenTypes.SINGLE_LINE_COMMENT); filter.hide(TokenTypes.BLOCK_COMMENT_BEGIN); final GeneratedJavaRecognizer parser = new GeneratedJavaRecognizer(filter); parser.setFilename(contents.getFileName()); parser.setASTNodeClass(DetailAST.class.getName()); try { parser.compilationUnit(); } catch (RecognitionException | TokenStreamException ex) { final String exceptionMsg = String.format(Locale.ROOT, "%s occurred while parsing file %s.", ex.getClass().getSimpleName(), contents.getFileName()); throw new CheckstyleException(exceptionMsg, ex); } return (DetailAST) parser.getAST(); }
@Override protected void finishLocalSetup() throws CheckstyleException { final Locale locale = new Locale(localeLanguage, localeCountry); LocalizedMessage.setLocale(locale); if (moduleFactory == null) { if (moduleClassLoader == null) { throw new CheckstyleException( "if no custom moduleFactory is set, " + "moduleClassLoader must be specified"); } final Set<String> packageNames = PackageNamesLoader .getPackageNames(moduleClassLoader); moduleFactory = new PackageObjectFactory(packageNames, moduleClassLoader); } final DefaultContext context = new DefaultContext(); context.add("charset", charset); context.add("classLoader", classLoader); context.add("moduleFactory", moduleFactory); context.add("severity", severity.getName()); context.add("basedir", basedir); childContext = context; }