diff --git a/.github/actions/test-plugin-installation/Dockerfile b/.github/actions/test-plugin-installation/Dockerfile index 6b8ffff5..31fb5cbb 100644 --- a/.github/actions/test-plugin-installation/Dockerfile +++ b/.github/actions/test-plugin-installation/Dockerfile @@ -2,7 +2,7 @@ # #%L # AEM Rules for SonarQube # %% -# Copyright (C) 2015-2019 Wunderman Thompson Technology +# Copyright (C) 2015-2024 VML # %% # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -26,4 +26,3 @@ ARG inputs_aem_rules_binary FROM $inputs_sonarqube_base_image COPY $inputs_aem_rules_binary $SONARQUBE_HOME/extensions/plugins/$inputs_aem_rules_binary -# COPY sonar-findbugs-plugin-3.11.0.jar $SONARQUBE_HOME/extensions/plugins/sonar-findbugs-plugin-3.11.0.jar \ No newline at end of file diff --git a/.github/actions/test-plugin-installation/action.yml b/.github/actions/test-plugin-installation/action.yml index 6bb27ddd..eee57d14 100644 --- a/.github/actions/test-plugin-installation/action.yml +++ b/.github/actions/test-plugin-installation/action.yml @@ -2,7 +2,7 @@ # #%L # AEM Rules for SonarQube # %% -# Copyright (C) 2015-2019 Wunderman Thompson Technology +# Copyright (C) 2015-2024 VML # %% # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ inputs: sonarqube-base-image: description: 'Which base Docker image to use to set up SonarQube' required: true - default: sonarqube-8.9-community + default: sonarqube-9.9-community aem-rules-binary: description: "Name of the JAR file to copy from Maven's 'target' directory into the plugins directory" required: true diff --git a/.github/actions/test-plugin-installation/run-tests.sh b/.github/actions/test-plugin-installation/run-tests.sh index 9c2c7d48..8ef5dc61 100755 --- a/.github/actions/test-plugin-installation/run-tests.sh +++ b/.github/actions/test-plugin-installation/run-tests.sh @@ -3,7 +3,7 @@ # #%L # AEM Rules for SonarQube # %% -# Copyright (C) 2015-2019 Wunderman Thompson Technology +# Copyright (C) 2015-2024 VML # %% # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ print_usage() { usage: $0 [IMAGE...] examples: - $0 7.6-community + $0 9.9-community EOF } diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 79bc961d..736ca4e8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -2,7 +2,7 @@ # #%L # AEM Rules for SonarQube # %% -# Copyright (C) 2015-2019 Wunderman Thompson Technology +# Copyright (C) 2015-2024 VML # %% # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ name: build-and-analyse -on: [push] +on: [ push ] jobs: build: @@ -28,26 +28,17 @@ jobs: strategy: matrix: - java-version: [11] + java-version: [ 11 ] steps: - - uses: actions/checkout@v3 - - uses: actions/setup-java@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 with: java-version: ${{ matrix.java-version }} distribution: 'adopt' cache: maven - - name: Package the Maven project and analyse the AEM Rules code with SonarCloud - # The Sonar plugin automatically picks up the token from an env variable. - # See https://docs.sonarcloud.io/advanced-setup/ci-based-analysis/sonarscanner-for-maven/#configuration - # See https://docs.github.com/en/actions/security-guides/automatic-token-authentication + - name: Package the Maven project and analyse the AEM Rules code env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONARCLOUD_KEY }} run: | - mvn clean package \ - org.jacoco:jacoco-maven-plugin:report \ - org.eluder.coveralls:coveralls-maven-plugin:report \ - sonar:sonar -Dsonar.host.url=https://sonarcloud.io \ - -Dsonar.organization=wttech \ - -Dsonar.projectKey=wttech_AEM-Rules-for-SonarQube + mvn clean package jacoco:report coveralls:report diff --git a/.github/workflows/test-instalation.yml b/.github/workflows/test-instalation.yml index 328ff7df..161bf9a7 100644 --- a/.github/workflows/test-instalation.yml +++ b/.github/workflows/test-instalation.yml @@ -2,7 +2,7 @@ # #%L # AEM Rules for SonarQube # %% -# Copyright (C) 2015-2019 Wunderman Thompson Technology +# Copyright (C) 2015-2024 VML # %% # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -29,8 +29,8 @@ jobs: strategy: matrix: sonarqube-image: - - 'sonarqube:8.9-community' - - 'sonarqube:9.4-community' + - 'sonarqube:9.9-community' + - 'sonarqube:10.7-community' - 'sonarqube:lts-community' - 'sonarqube:latest' fail-fast: false @@ -38,8 +38,8 @@ jobs: # To use this repository's private action, # you must check out the repository - name: Checkout - uses: actions/checkout@v3 - - uses: actions/setup-java@v3 + uses: actions/checkout@v4 + - uses: actions/setup-java@v4 with: java-version: 11 distribution: 'adopt' @@ -58,4 +58,4 @@ jobs: sonarqube-base-image: ${{ matrix.sonarqube-image }} aem-rules-binary: ${{ steps.get-executable-name.outputs.aem_rules_jar_name }} docker-hub-login: ${{ secrets.DOCKER_HUB_USERNAME }} - docker-hub-token: ${{ secrets.DOCKER_HUB_TOKEN }} \ No newline at end of file + docker-hub-token: ${{ secrets.DOCKER_HUB_TOKEN }} diff --git a/.gitignore b/.gitignore index f1b8171a..b4c123c6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,23 @@ +node_modules +.DS_Store +target/ +node/ .idea/ +sonar-example-plugin.iml +.java-version +local-docker-image/extensions/plugins/* *.iml -*.ipr -*.iws -target/ -atlassian-ide-plugin.xml + +# Eclipse .classpath .project .settings/ -.java-version -.DS_Store + +# yarn +.yarn/* +!.yarn/cache +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/sdks +!.yarn/versions \ No newline at end of file diff --git a/README.md b/README.md index 27f6da0f..8e5606e7 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,18 @@ -[![Wunderman Thompson Technology logo](assets/wtt-logo.png)](http://www.cognifide.com/) +[](http://www.vml.com/poland) + ![Builds Status](https://github.com/wttech/AEM-Rules-for-SonarQube/actions/workflows/build.yml/badge.svg) [![Coverage Status](https://coveralls.io/repos/github/Cognifide/AEM-Rules-for-SonarQube/badge.svg?branch=master)](https://coveralls.io/github/Cognifide/AEM-Rules-for-SonarQube?branch=master) -[![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=AEM-Rules-for-SonarQube&metric=alert_status)](https://sonarcloud.io/dashboard?id=AEM-Rules-for-SonarQube) +[Available in SonarLint](https://www.sonarlint.org/) +[Available in SonarCloud](https://sonarcloud.io) +[Available in SonarQube](https://www.sonarqube.org/) # About AEM Rules for SonarQube ![AEM Rules for SonarQube](https://raw.githubusercontent.com/wttech/AEM-Rules-for-SonarQube/master/assets/logo.png) ## Purpose -As we all know, SonarQube is a great tool that helps us increase quality of our codebase. However, it does apply mainly to general Java issues. As we know, we can hurt ourselves much more doing AEM. [Adobe Experience Manager](https://docs.adobe.com/docs/en/aem/6-2.html) is a comprehensive content management platform solution for building websites, mobile apps and forms. This tool is intended to find common bugs and bad smells specific for AEM development. Documentation of each rule is available from SonarQube interface after plugin installation. +As we all know, SonarQube is a great tool that helps us increase quality of our codebase. However, it does apply mainly to general Java issues. As we know, we can hurt ourselves much more doing AEM. [Adobe Experience Manager](https://experienceleague.adobe.com/en/docs) is a comprehensive content management platform solution for building websites, mobile apps and forms. This tool is intended to find common bugs and bad smells specific for AEM development. Documentation of each rule is available from SonarQube interface after plugin installation. ## Prerequisites @@ -17,25 +20,16 @@ Each release has its own prerequisites section, for more information please chec ## Installation -**Custom Dockerfile** +### Local docker image -Following Dockerfile uses official Sonarqube 7.9 image and download AEM Rules 1.0-RC2 to plugin directory. +Check the plugin locally with the prepared ```docker-compose.yml```. Just run these commands from the repo root to build the latest package and fire up a container. ``` -FROM sonarqube:7.9-community AS aemrulesqube79 -RUN curl -Lk -o $SONARQUBE_HOME/extensions/plugins/aemrules-1.0-RC2.jar https://github.com/wttech/AEM-Rules-for-SonarQube/releases/download/v1.0-RC2/aemrules-1.0-RC2.jar +mvn clean package +cd local-docker-image +docker-compose up -d ``` -**Community image** - -This is already prepared solution thanks to @ahmed-musallam. - -`docker run --rm -p 9000:9000 ahmedmusallam/sonarqube-aem:latest` - -This solution is for those who would like to start testing theirs code within aem rules and sonarqube. It contains SonarQube v 7.7, aem rules v 0.11 and predefined quality gates. -If you would like to participate in our Aem Rules development, please refer to [wiki page](https://github.com/wttech/AEM-Rules-for-SonarQube/wiki) to get into. - - ### Update Center Go to your SonarQube instance administration console and open Update Center. Find AEM Rules for SonarQube plugin and click install! @@ -52,7 +46,6 @@ Go to your SonarQube instance administration console and open Update Center. Fin Use of the plugin does not differ much from regular SonarQube analysis. However, as rules are often tied to a certain AEM version and its components (Felix, Sling), we've introduced the `aemVersion` analysis property. Each rule defines supported AEM version or version range. Most of the rules are universal. -By providing the AEM version parameter, you can instruct the Sonar Runner to only use only a subset of rules applicable to a particular AEM version. When the parameter is not provided then a default AEM version is used (currently 6.4) ### Running analysis @@ -60,14 +53,19 @@ When running analysis, pass `sonarRunner.aemVersion` property with your AEM vers `sonarRunner.aemVersion=.` -Runing with Maven -``` -mvn sonar:sonar -DsonarRunner.aemVersion=6.4 -``` +To avoid quality profiles collisions, the additional execution param has been added. + +`-Dsonar.html.file.suffixes=.notexistingsuffix` -Runing with Gradle (See [Gradle AEM Plugin](https://github.com/wttech/gradle-aem-plugin)) +Running with Maven ``` -gradlew sonarQube -DsonarRunner.aemVersion=6.4 +mvn clean verify sonar:sonar \ + -Dsonar.projectKey={sonar_project_key} \ + -Dsonar.projectName='{sonar_project_name}' \ + -Dsonar.host.url=http://localhost:9000 \ + -Dsonar.token={sonar_project_token} \ + -DsonarRunner.aemVersion=6.5 \ + -Dsonar.html.file.suffixes=.notexistingsuffix ``` # Rule set @@ -180,13 +178,13 @@ Release notes for each version can be found in [releases section](https://github # License -Copyright 2015-2016 Wunderman Thompson Technology +Copyright 2015-2024 VML Licensed under the Apache License, Version 2.0 # Commercial Support -Technical support can be made available if needed. Please [contact us](mailto:labs-support@cognifide.com) for more details. +Technical support can be made available if needed. Please [contact us](mailto:labs-support@wundermanthompson.com) for more details. We can: diff --git a/assets/license-template.txt b/assets/license-template.txt index 7acb61a7..38d31a4c 100644 --- a/assets/license-template.txt +++ b/assets/license-template.txt @@ -1,7 +1,7 @@ #%L ${project.name} %% -Copyright (C) ${project.inceptionYear}-2019 Wunderman Thompson Technology +Copyright (C) ${project.inceptionYear}-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/assets/vml-logo.png b/assets/vml-logo.png new file mode 100644 index 00000000..c1c4ce2a Binary files /dev/null and b/assets/vml-logo.png differ diff --git a/assets/wtt-logo.png b/assets/wtt-logo.png deleted file mode 100644 index aba03ebf..00000000 Binary files a/assets/wtt-logo.png and /dev/null differ diff --git a/local-docker-image/conf/sonar.properties b/local-docker-image/conf/sonar.properties new file mode 100644 index 00000000..34ac760e --- /dev/null +++ b/local-docker-image/conf/sonar.properties @@ -0,0 +1,449 @@ +# +# #%L +# AEM Rules for SonarQube +# %% +# Copyright (C) 2015-2024 VML +# %% +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# #L% +# + +#-------------------------------------------------------------------------------------------------- +# IMPORTANT: +# This file will *not* be reloaded upon hitting the "Restart" button in the UI, or using the +# api/system/restart endpoint. +# In order for any change made to this file to be taken into account, you must perform a full +# restart of the main SonarQube service. +#-------------------------------------------------------------------------------------------------- + +# Property values can: +# - be overridden by environment variables. The name of the corresponding environment variable is the +# upper-cased name of the property where all the dot ('.') and dash ('-') characters are replaced by +# underscores ('_'). For example, to override 'sonar.web.systemPasscode' use 'SONAR_WEB_SYSTEMPASSCODE'. +# - be encrypted. See https://docs.sonarqube.org/latest/instance-administration/security/#settings-encryption + +#-------------------------------------------------------------------------------------------------- +# DATABASE +# +# IMPORTANT: +# - The embedded H2 database is used by default. It is recommended for tests but not for +# production use. Supported databases are Oracle, PostgreSQL and Microsoft SQLServer. +# - Changes to database connection URL (sonar.jdbc.url) can affect SonarSource licensed products. + +# User credentials. +# Permissions to create tables, indices and triggers must be granted to JDBC user. +# The schema must be created first. +#sonar.jdbc.username= +#sonar.jdbc.password= + +#----- Embedded Database (default) +# H2 embedded database server listening port, defaults to 9092 +#sonar.embeddedDatabase.port=9092 + + +#----- Oracle 19c/21c +# The Oracle JDBC driver must be copied into the directory extensions/jdbc-driver/oracle/. +# Only the thin client is supported, and we recommend using the latest Oracle JDBC driver. See +# https://jira.sonarsource.com/browse/SONAR-9758 for more details. +# If you need to set the schema, please refer to http://jira.sonarsource.com/browse/SONAR-5000 +#sonar.jdbc.url=jdbc:oracle:thin:@localhost:1521/XE + + +#----- PostgreSQL 11 or greater +# By default the schema named "public" is used. It can be overridden with the parameter "currentSchema". +#sonar.jdbc.url=jdbc:postgresql://localhost/sonarqube?currentSchema=my_schema + + +#----- Microsoft SQLServer 2014/2016/2017/2019/2022 and SQL Azure +# A database named sonar must exist and its collation must be case-sensitive (CS) and accent-sensitive (AS) +# Use the following connection string if you want to use integrated security with Microsoft Sql Server +# Do not set sonar.jdbc.username or sonar.jdbc.password property if you are using Integrated Security +# For Integrated Security to work, you have to download the Microsoft SQL JDBC Auth 11.2.2 package from +# https://github.com/microsoft/mssql-jdbc/releases/download/v11.2.2/mssql-jdbc_auth.zip +# and 'mssql-jdbc_auth-11.2.2.x64.dll' to your path. +#sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonar;integratedSecurity=true + +# Use the following connection string if you want to use SQL Auth while connecting to MS Sql Server. +# Set the sonar.jdbc.username and sonar.jdbc.password appropriately. +#sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonar + + +#----- Connection pool settings +# The maximum number of active connections that can be allocated +# at the same time, or negative for no limit. +# The recommended value is 1.2 * max sizes of HTTP pools. For example if HTTP ports are +# enabled with default sizes (50, see property sonar.web.http.maxThreads) +# then sonar.jdbc.maxActive should be 1.2 * 50 = 60. +#sonar.jdbc.maxActive=60 + +# The minimum number of connections that can remain idle in the pool, +# without extra ones being created, or zero to create none. +#sonar.jdbc.minIdle=10 + +# The maximum number of milliseconds that the pool will wait (when there +# are no available connections) for a connection to be returned before +# throwing an exception, or <= 0 to wait indefinitely. +#sonar.jdbc.maxWait=8000 + + +#-------------------------------------------------------------------------------------------------- +# WEB SERVER +# Web server is executed in a dedicated Java process. By default heap size is 512MB. +# Use the following property to customize JVM options. +# Recommendations: +# +# The HotSpot Server VM is recommended. The property -server should be added if server mode +# is not enabled by default on your environment: +# http://docs.oracle.com/javase/8/docs/technotes/guides/vm/server-class.html +# +# Startup can be long if entropy source is short of entropy. Adding +# -Djava.security.egd=file:/dev/./urandom is an option to resolve the problem. +# See https://wiki.apache.org/tomcat/HowTo/FasterStartUp#Entropy_Source +# +#sonar.web.javaOpts=-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError + +# Same as previous property, but allows to not repeat all other settings like -Xmx +#sonar.web.javaAdditionalOpts= + +# Binding IP address. For servers with more than one IP address, this property specifies which +# address will be used for listening on the specified ports. +# By default, ports will be used on all IP addresses associated with the server. +#sonar.web.host=0.0.0.0 + +# Web context. When set, it must start with forward slash (for example /sonarqube). +# Changing this value and restarting the server can have unexpected consequences for logged in users, +# as they may end up with multiple conflicting browser cookies. If your users experience odd +# behaviors after you changed this value and restarted the server, ask them to clear their browser's +# cookies and log in again. +# The default value is root context (empty value). +#sonar.web.context= +# TCP port for incoming HTTP connections. Default value is 9000. +#sonar.web.port=9000 + + +# The maximum number of connections that the server will accept and process at any given time. +# When this number has been reached, the server will not accept any more connections until +# the number of connections falls below this value. The operating system may still accept connections +# based on the sonar.web.connections.acceptCount property. The default value is 50. +#sonar.web.http.maxThreads=50 + +# The minimum number of threads always kept running. The default value is 5. +#sonar.web.http.minThreads=5 + +# The maximum queue length for incoming connection requests when all possible request processing +# threads are in use. Any requests received when the queue is full will be refused. +# The default value is 25. +#sonar.web.http.acceptCount=25 + +# The number of milliseconds this Connector will wait for another HTTP request before closing the +# connection. The default value is to use the value that has been set for the connectionTimeout +# attribute. Use a value of -1 to indicate no (i.e. infinite) timeout. +# The default value is 60000 (ms). +#sonar.web.http.keepAliveTimeout=60000 + +# By default users are logged out and sessions closed when server is restarted. +# If you prefer keeping user sessions open, a secret should be defined. Value is +# HS256 key encoded with base64. It must be unique for each installation of SonarQube. +# Example of command-line: +# echo -n "type_what_you_want" | openssl dgst -sha256 -hmac "key" -binary | base64 +#sonar.auth.jwtBase64Hs256Secret= + +# The inactivity timeout duration of user sessions, in minutes. After the configured +# period of time, the user is logged out. +# The default value is set to 3 days (4320 minutes). +# It must be set between 6 minutes and 3 months (129600 minutes). +# Value must be strictly positive. +#sonar.web.sessionTimeoutInMinutes=4320 + +# A passcode can be defined to access some web services from monitoring +# tools without having to use the credentials of a system administrator. +# Check the Web API documentation to know which web services are supporting this authentication mode. +# The passcode should be provided in HTTP requests with the header "X-Sonar-Passcode". +# By default feature is disabled. +#sonar.web.systemPasscode= + + +#-------------------------------------------------------------------------------------------------- +# SSO AUTHENTICATION + +# Enable authentication using HTTP headers +#sonar.web.sso.enable=false + +# Name of the header to get the user login. +# Only alphanumeric, '.' and '@' characters are allowed +#sonar.web.sso.loginHeader=X-Forwarded-Login + +# Name of the header to get the user name +#sonar.web.sso.nameHeader=X-Forwarded-Name + +# Name of the header to get the user email (optional) +#sonar.web.sso.emailHeader=X-Forwarded-Email + +# Name of the header to get the list of user groups, separated by comma (optional). +# If the sonar.sso.groupsHeader is set, the user will belong to those groups if groups exist in SonarQube. +# If none of the provided groups exists in SonarQube, the user will only belong to the default group. +# Note that the default group will always be set. +#sonar.web.sso.groupsHeader=X-Forwarded-Groups + +# Interval used to know when to refresh name, email and groups. +# During this interval, if for instance the name of the user is changed in the header, it will only be updated after X minutes. +#sonar.web.sso.refreshIntervalInMinutes=5 + +#-------------------------------------------------------------------------------------------------- +# LDAP CONFIGURATION + +# Enable the LDAP feature +# sonar.security.realm=LDAP + +# Set to true when connecting to a LDAP server using a case-insensitive setup. +# sonar.authenticator.downcase=true + +# URL of the LDAP server. Note that if you are using ldaps, then you should install the server certificate into the Java truststore. +# ldap.url=ldap://localhost:10389 + +# Bind DN is the username of an LDAP user to connect (or bind) with. Leave this blank for anonymous access to the LDAP directory (optional) +# ldap.bindDn=cn=sonar,ou=users,o=mycompany + +# Bind Password is the password of the user to connect with. Leave this blank for anonymous access to the LDAP directory (optional) +# ldap.bindPassword=secret + +# Possible values: simple | CRAM-MD5 | DIGEST-MD5 | GSSAPI See http://java.sun.com/products/jndi/tutorial/ldap/security/auth.html (default: simple) +# ldap.authentication=simple + +# See : +# * http://java.sun.com/products/jndi/tutorial/ldap/security/digest.html +# * http://java.sun.com/products/jndi/tutorial/ldap/security/crammd5.html +# (optional) +# ldap.realm=example.org + +# Context factory class (optional) +# ldap.contextFactoryClass=com.sun.jndi.ldap.LdapCtxFactory + +# Enable usage of StartTLS (default : false) +# ldap.StartTLS=true + +# Follow or not referrals. See http://docs.oracle.com/javase/jndi/tutorial/ldap/referral/jndi.html (default: true) +# ldap.followReferrals=false + +# USER MAPPING + +# Distinguished Name (DN) of the root node in LDAP from which to search for users (mandatory) +# ldap.user.baseDn=cn=users,dc=example,dc=org + +# LDAP user request. (default: (&(objectClass=inetOrgPerson)(uid={login})) ) +# ldap.user.request=(&(objectClass=user)(sAMAccountName={login})) + +# Attribute in LDAP defining the user?s real name. (default: cn) +# ldap.user.realNameAttribute=name + +# Attribute in LDAP defining the user?s email. (default: mail) +# ldap.user.emailAttribute=email + +# GROUP MAPPING + +# Distinguished Name (DN) of the root node in LDAP from which to search for groups. (optional, default: empty) +# ldap.group.baseDn=cn=groups,dc=example,dc=org + +# LDAP group request (default: (&(objectClass=groupOfUniqueNames)(uniqueMember={dn})) ) +# ldap.group.request=(&(objectClass=group)(member={dn})) + +# Property used to specifiy the attribute to be used for returning the list of user groups in the compatibility mode. (default: cn) +# ldap.group.idAttribute=sAMAccountName + +#-------------------------------------------------------------------------------------------------- +# COMPUTE ENGINE +# The Compute Engine is responsible for processing background tasks. +# Compute Engine is executed in a dedicated Java process. Default heap size is 512MB. +# Use the following property to customize JVM options. +# Recommendations: +# +# The HotSpot Server VM is recommended. The property -server should be added if server mode +# is not enabled by default on your environment: +# http://docs.oracle.com/javase/8/docs/technotes/guides/vm/server-class.html +# +#sonar.ce.javaOpts=-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError + +# Same as previous property, but allows to not repeat all other settings like -Xmx +#sonar.ce.javaAdditionalOpts= + + +#-------------------------------------------------------------------------------------------------- +# ELASTICSEARCH +# Elasticsearch is used to facilitate fast and accurate information retrieval. +# It is executed in a dedicated Java process. Default maximum heap size is 512MB. +# It is recommended to also set MaxDirectMemorySize (-XX:MaxDirectMemorySize) and set it to half the maximum heap size. +# +# -------------------------------------------------- +# Word of caution for Linux users on 64bits systems +# -------------------------------------------------- +# Please ensure Virtual Memory on your system is correctly configured for Elasticsearch to run properly +# (see https://www.elastic.co/guide/en/elasticsearch/reference/5.5/vm-max-map-count.html for details). +# +# When SonarQube runs standalone, a warning such as the following may appear in logs/es.log: +# "max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]" +# When SonarQube runs as a cluster, however, Elasticsearch will refuse to start. +# + +# JVM options of Elasticsearch process +#sonar.search.javaOpts=-Xmx512m -Xms512m -XX:MaxDirectMemorySize=256m -XX:+HeapDumpOnOutOfMemoryError + +# Same as previous property, but allows to not repeat all other settings like -Xmx +#sonar.search.javaAdditionalOpts= + +# Elasticsearch port for incoming HTTP connections. Default is 9001. Use 0 to get a free port. +# As a security precaution, should be blocked by a firewall and not exposed to the Internet. +#sonar.search.port=9001 + +# Elasticsearch TCP transport port that is bound to loopback address. When nothing is set, a random port will be chosen. +# As a security precaution, your OS configuration should not expose this port for external access. +#sonar.es.port= + +# Elasticsearch host. The search server will bind this address and the search client will connect to it. +# Default is loopback address. +# As a security precaution, should NOT be set to a publicly available address. +#sonar.search.host= + + +#-------------------------------------------------------------------------------------------------- +# UPDATE CENTER + +# Update Center requires an internet connection to request https://update.sonarsource.org +# It is enabled by default. +#sonar.updatecenter.activate=true + +# HTTP proxy (default none) +#http.proxyHost= +#http.proxyPort= +# HTTPS proxy (defaults are values of http.proxyHost and http.proxyPort) +#https.proxyHost= +#https.proxyPort= + +# NT domain name if NTLM proxy is used +#http.auth.ntlm.domain= + +# SOCKS proxy (default none) +#socksProxyHost= +#socksProxyPort= + +# Proxy authentication (used for HTTP, HTTPS and SOCKS proxies) +#http.proxyUser= +#http.proxyPassword= + +# Proxy exceptions: list of hosts that can be accessed without going through the proxy +# separated by the '|' character, wildcard character '*' can be used for pattern matching +# used for HTTP and HTTPS (default none) +# (note: localhost and its literal notations (127.0.0.1, ...) are always excluded) +#http.nonProxyHosts= + + +#-------------------------------------------------------------------------------------------------- +# LOGGING + +# SonarQube produces logs in 4 logs files located in the same directory (see property sonar.path.logs below), +# one per process: +# Main process (aka. App) logs in sonar.log +# Web Server (aka. Web) logs in web.log +# Compute Engine (aka. CE) logs in ce.log +# Elasticsearch (aka. ES) logs in es.log +# +# Depending on the startup, all 4 files follow the same rolling policy (see sonar.log.rollingPolicy and sonar.log.maxFiles) but it applies +# individually (eg. if sonar.log.maxFiles=4, there can be at most 4 of each files, ie. 16 files in total). +# +# All 4 files have logs in the same format: +# 1 2 3 4 5 6 +# |-----------------| |---| |-|--------------------||------------------------------| |------------------------------------------------------------------------------------------------------------------------------| +# 2016.11.16 16:47:00 INFO ce[AVht0dNXFcyiYejytc3m][o.s.s.c.t.CeWorkerCallableImpl] Executed task | project=org.sonarqube:example-java-maven | type=REPORT | id=AVht0dNXFcyiYejytc3m | submitter=admin | time=1699ms +# +# 1: timestamp. Format is YYYY.MM.DD HH:MM:SS +# YYYY: year on 4 digits +# MM: month on 2 digits +# DD: day on 2 digits +# HH: hour of day on 2 digits in 24 hours format +# MM: minutes on 2 digits +# SS: seconds on 2 digits +# 2: log level. +# Possible values (in order of descending criticality): ERROR, WARN, INFO, DEBUG and TRACE +# 3: process identifier. Possible values: app (main), web (Web Server), ce (Compute Engine) and es (Elasticsearch) +# 4: SQ thread identifier. Can be empty. +# In the Web Server, if present, it will be the HTTP request ID. +# In the Compute Engine, if present, it will be the task ID. +# 5: logger name. Usually a class canonical name. +# Package names are truncated to keep the whole field to 20 characters max +# 6: log payload. Content of this field does not follow any specific format, can vary in length and include line returns. +# Some logs, however, will follow the convention to provide data in payload in the format " | key=value" +# Especially, log of profiled pieces of code will end with " | time=XXXXms". + +# Global level of logs (applies to all 4 processes). +# Supported values are INFO (default), DEBUG and TRACE +#sonar.log.level=INFO + +# Level of logs of each process can be controlled individually with their respective properties. +# When specified, they overwrite the level defined at global level. +# Supported values are INFO, DEBUG and TRACE +#sonar.log.level.app=INFO +#sonar.log.level.web=INFO +#sonar.log.level.ce=INFO +#sonar.log.level.es=INFO + +# Path to log files. Can be absolute or relative to installation directory. +# Default is /logs +#sonar.path.logs=logs + +# Rolling policy of log files +# - based on time if value starts with "time:", for example by day ("time:yyyy-MM-dd") +# or by month ("time:yyyy-MM") +# - based on size if value starts with "size:", for example "size:10MB" +# - disabled if value is "none". That needs logs to be managed by an external system like logrotate. +#sonar.log.rollingPolicy=time:yyyy-MM-dd + +# Maximum number of files to keep if a rolling policy is enabled. +# - maximum value is 20 on size rolling policy +# - unlimited on time rolling policy. Set to zero to disable old file purging. +#sonar.log.maxFiles=7 + +# Access log is the list of all the HTTP requests received by server. If enabled, it is stored +# in the file {sonar.path.logs}/access.log. This file follows the same rolling policy as other log file +# (see sonar.log.rollingPolicy and sonar.log.maxFiles). +#sonar.web.accessLogs.enable=true + +# Format of access log. It is ignored if sonar.web.accessLogs.enable=false. Possible values are: +# - "common" is the Common Log Format, shortcut to: %h %l %u %user %date "%r" %s %b +# - "combined" is another format widely recognized, shortcut to: %h %l %u [%t] "%r" %s %b "%i{Referer}" "%i{User-Agent}" +# - else a custom pattern. See http://logback.qos.ch/manual/layouts.html#AccessPatternLayout. +# The login of authenticated user is not implemented with "%u" but with "%reqAttribute{LOGIN}" (since version 6.1). +# The value displayed for anonymous users is "-". +# The SonarQube's HTTP request ID can be added to the pattern with "%reqAttribute{ID}" (since version 6.2). +# If SonarQube is behind a reverse proxy, then the following value allows to display the correct remote IP address: +#sonar.web.accessLogs.pattern=%i{X-Forwarded-For} %l %u [%t] "%r" %s %b "%i{Referer}" "%i{User-Agent}" "%reqAttribute{ID}" +# Default value (which was "combined" before version 6.2) is equivalent to "combined + SQ HTTP request ID": +#sonar.web.accessLogs.pattern=%h %l %u [%t] "%r" %s %b "%i{Referer}" "%i{User-Agent}" "%reqAttribute{ID}" + + +#-------------------------------------------------------------------------------------------------- +# OTHERS + +# Delay in seconds between processing of notification queue. Default is 60 seconds. +#sonar.notifications.delay=60 + +# Paths to persistent data files (embedded database and search index) and temporary files. +# Can be absolute or relative to installation directory. +# Defaults are respectively /data and /temp +#sonar.path.data=data +#sonar.path.temp=temp + +# Telemetry - Share anonymous SonarQube statistics +# By sharing anonymous SonarQube statistics, you help us understand how SonarQube is used so we can improve the product to work even better for you. +# We don't collect source code or IP addresses. And we don't share the data with anyone else. +#sonar.telemetry.enable=true + +sonar.web.javaAdditionalOpts=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000 diff --git a/local-docker-image/docker-compose.yml b/local-docker-image/docker-compose.yml new file mode 100644 index 00000000..d6bd0000 --- /dev/null +++ b/local-docker-image/docker-compose.yml @@ -0,0 +1,34 @@ +# +# #%L +# AEM Rules for SonarQube +# %% +# Copyright (C) 2015-2024 VML +# %% +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# #L% +# + +name: sonar-local + +services: + sonar-local: + image: sonarqube:10.7-community + build: + context: . + ports: + - "9000:9000" + - "8000:8000" + restart: unless-stopped + volumes: + - ./extensions/plugins:/opt/sonarqube/extensions/plugins:ro + - ./conf:/opt/sonarqube/conf:ro diff --git a/pom.xml b/pom.xml index 0e816287..d259f9c9 100644 --- a/pom.xml +++ b/pom.xml @@ -1,466 +1,449 @@ - - 4.0.0 + + 4.0.0 - com.cognifide.aemrules - sonar-aemrules-plugin - 1.7-SNAPSHOT + com.vml.aemrules + sonar-aemrules-plugin + sonar-plugin + 1.7-SNAPSHOT - AEM Rules for SonarQube - SonarQube plugin with set of rules detecting possible bugs and bad smells specific - for AEM - development. - + AEM Rules for SonarQube + SonarQube plugin with set of rules detecting possible bugs and bad smells specific for AEM development. - sonar-plugin + 2015 + + VML + https://www.vml.com/poland/ + - 2015 - - Wunderman Thompson Technology - http://www.cognifide.com - + + + The Apache Software License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0.txt + repo + + - - - The Apache Software License, Version 2.0 - https://www.apache.org/licenses/LICENSE-2.0.txt - repo - - + + + michal.chudy + Michal Chudy + michal.chudy@cognifide.com + + + szymon.owczarzak + Szymon Owczarzak + szymon.owczarzak@cognifide.com + + + piotr.wilczynski + Piotr Wilczyński + piotr.wilczynski@cognifide.com + + + michal.tobiasz + Michał Tobiasz + michal.tobiasz@cognifide.com + + + mateusz.bartkowiak + Mateusz Bartkowiak + mateusz.bartkowiak@cognifide.com + + + jedrzej.plucinski + Jędrzej Pluciński + jedrzej.plucinski@cognifide.com + + + krystian.panek + Krystian Panek + krystian.panek@cognifide.com + + + tomasz.strzelecki + Tomasz Strzelecki + tomasz.strzelecki@vml.com + + - - - michal.chudy - Michal Chudy - michal.chudy@cognifide.com - - - szymon.owczarzak - Szymon Owczarzak - szymon.owczarzak@cognifide.com - - - piotr.wilczynski - Piotr Wilczyński - piotr.wilczynski@cognifide.com - - - michal.tobiasz - Michał Tobiasz - michal.tobiasz@cognifide.com - - - mateusz.bartkowiak - Mateusz Bartkowiak - mateusz.bartkowiak@cognifide.com - - - jedrzej.plucinski - Jędrzej Pluciński - jedrzej.plucinski@cognifide.com - - - krystian.panek - Krystian Panek - krystian.panek@cognifide.com - - + + + Krzysztof Malinowski + krzysztof.malinowski@motorolasolutions.com + Motorola Solutions, Inc. + https://www.motorolasolutions.com + + - - - Krzysztof Malinowski - krzysztof.malinowski@motorolasolutions.com - Motorola Solutions, Inc. - https://www.motorolasolutions.com - - + + scm:git:git@github.com:wttech/AEM-Rules-for-SonarQube.git + scm:git:git@github.com:wttech/AEM-Rules-for-SonarQube.git + scm:git:git@github.com:wttech/AEM-Rules-for-SonarQube.git + HEAD + - - scm:git:git@github.com:wttech/AEM-Rules-for-SonarQube.git - scm:git:git@github.com:wttech/AEM-Rules-for-SonarQube.git - scm:git:git@github.com:wttech/AEM-Rules-for-SonarQube.git - - HEAD - + + jira + https://github.com/wttech/AEM-Rules-for-SonarQube/issues + - - jira - https://github.com/wttech/AEM-Rules-for-SonarQube/issues - + + + cognifide-internal-repository + Cognifide Internal Repository + https://nexus.cognifide.com/content/repositories/cognifide-internal + + + cognifide-internal-snapshots-repository + Cognifide Internal Repository + https://nexus.cognifide.com/content/repositories/cognifide-internal-snapshots + + - - - cognifide-internal-repository - Cognifide Internal Repository - https://nexus.cognifide.com/content/repositories/cognifide-internal - - - cognifide-internal-snapshots-repository - Cognifide Internal Repository - https://nexus.cognifide.com/content/repositories/cognifide-internal-snapshots - - + + 1.1.2-1.4.0 + 3.15.0.5107 + 7.30.1.34514 + UTF-8 + 10.11.0.2468 + 10.3.0.82913 + 10.7.0.96327 + 7.30.1.34514 + 11 + src/main/java + 4rVf3NGV0jyQ3EGrc8L86oEDoHWm6MgDD + v${project.version} + - - UTF-8 - 1.1.2-1.4.0 - 8.9.6.50800 - 3.0.1.1444 - 7.6.0.28201 - 7.6.0.28201 - 4rVf3NGV0jyQ3EGrc8L86oEDoHWm6MgDD - v${project.version} - + + + central + https://repo.maven.apache.org/maven2/ + + + adobe-releases + https://repo.adobe.com/nexus/content/groups/public/ + + - - - central - https://repo.maven.apache.org/maven2/ - - - adobe-releases - https://repo.adobe.com/nexus/content/groups/public/ - - + + + + sonar-plugin-api + org.sonarsource.api.plugin + provided + ${sonar.pluginApiVersion} + + + sonar-html-plugin + org.sonarsource.html + ${sonar.html.version} + + + sonar-analyzer-commons + org.sonarsource.analyzer-commons + 2.14.0.3087 + + + sonar-java-plugin + org.sonarsource.java + sonar-plugin + ${sonar.java.plugin} + + + commons-lang3 + org.apache.commons + 3.17.0 + + + commons-io + commons-io + 2.17.0 + + + annotations + org.jetbrains + 26.0.1 + + + org.apache.sling.scripting.sightly.compiler + org.apache.sling + ${htl.version} + - - - commons-io - commons-io - 2.5 - - - org.apache.sling - org.apache.sling.scripting.sightly.compiler - ${htl.version} - + + + sonar-testing-harness + org.sonarsource.sonarqube + test + ${sonar.testingHarnessVersion} + + + junit-jupiter-api + org.junit.jupiter + test + 5.11.3 + + + junit-jupiter-params + org.junit.jupiter + test + 5.11.3 + + + mockito-core + org.mockito + test + 5.14.2 + + + assertj-core + org.assertj + test + 3.26.3 + + + guava + com.google.guava + test + 33.3.1-jre + + + sonar-plugin-api-impl + org.sonarsource.sonarqube + test + ${sonar.pluginApiImplVersion} + + + java-checks-testkit + org.sonarsource.java + test + ${sonar.javaCheksTestkitVersion} + + + logback-classic + ch.qos.logback + test + 1.5.12 + + + + aem-api + com.adobe.aem + test + 6.0.0.1 + + + jcr + javax.jcr + test + 2.0 + + + servlet-api + javax.servlet + test + 2.5 + + + org.apache.felix.scr.annotations + org.apache.felix + test + 1.12.0 + + + org.apache.sling.servlets.resolver + org.apache.sling + test + 2.3.2 + + + org.apache.sling.api + org.apache.sling + test + 2.4.0 + + + org.apache.sling.models.api + org.apache.sling + test + 1.3.8 + + + org.apache.sling.query + org.apache.sling + test + 4.0.2 + + + org.osgi.core + org.osgi + test + 6.0.0 + + + org.osgi.compendium + org.osgi + test + 5.0.0 + + + org.osgi.service.component.annotations + org.osgi + test + 1.5.0 + + - - - org.sonarsource.sonarqube - sonar-plugin-api - ${sonar.version} - provided - - - org.sonarsource.sonarqube - sonar-plugin-api-impl - ${sonar.version} - provided - - - - org.sonarsource.java - sonar-java-plugin - sonar-plugin - ${sonar.java.plugin} - provided - - - com.google.guava - guava - - - - - org.sonarsource.sslr-squid-bridge - sslr-squid-bridge - 2.6.1 - - - org.codehaus.sonar.sslr - sslr-core - - - org.codehaus.sonar - sonar-plugin-api - - - org.codehaus.sonar.sslr - sslr-xpath - - - org.slf4j - jcl-over-slf4j - - - org.slf4j - slf4j-api - - - - - org.apache.commons - commons-lang3 - 3.8.1 - - - org.sonarsource.html - sonar-html-plugin - ${sonar.html.version} - - - com.google.guava - guava - - - - - - - org.assertj - assertj-core - 3.6.2 - test - - - junit - junit - 4.13.1 - test - - - org.sonarsource.java - java-checks-testkit - ${sonar-java-checks-testkit-version} - test - - - org.easytesting - fest-assert - 1.4 - test - - - ch.qos.logback - logback-classic - 0.9.30 - test - - - com.adobe.aem - aem-api - 6.0.0.1 - test - - - javax.jcr - jcr - 2.0 - test - - - javax.servlet - servlet-api - 2.4 - test - - - org.apache.felix - org.apache.felix.scr.annotations - 1.9.4 - test - - - org.apache.sling - org.apache.sling.servlets.resolver - 2.3.2 - test - - - org.apache.sling - org.apache.sling.api - 2.4.0 - test - - - org.apache.sling - org.apache.sling.models.api - 1.1.0 - test - - - org.apache.sling - org.apache.sling.query - 4.0.2 - test - - - org.mockito - mockito-core - 2.21.0 - test - - - org.osgi - org.osgi.core - 4.2.0 - test - - - org.osgi - org.osgi.compendium - 4.2.0 - test - - - org.osgi - org.osgi.service.component.annotations - 1.3.0 - test - - - com.google.guava - guava - 26.0-jre - test - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 8 - 8 - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.0 - - 3 - true - - - @{argLine} -Xmx1024m -XX:MaxPermSize=256m - - - - - org.sonarsource.sonar-packaging-maven-plugin - sonar-packaging-maven-plugin - 1.18.0.372 - true - - aemrules - com.cognifide.aemrules.AemRulesSonarPlugin - ${project.name} - ${project.description} - https://github.com/wttech/AEM-Rules-for-SonarQube/issues - - https://github.com/wttech/AEM-Rules-for-SonarQube/tree/${tagName} - - https://github.com/wttech/AEM-Rules-for-SonarQube - false - 8.9 - true - - - - org.eluder.coveralls - coveralls-maven-plugin - 4.3.0 - - - - javax.xml.bind - jaxb-api - 2.3.1 - - - - ${coveralls.repo.token} - - - - org.jacoco - jacoco-maven-plugin - 0.8.5 - - - prepare-agent - - prepare-agent - - - - - - org.apache.maven.plugins - maven-release-plugin - 2.5.3 - - v@{project.version} - - - - com.mycila - license-maven-plugin - 3.0 - - false -
${basedir}/assets/license-template.txt
- -
${basedir}/assets/license-header-definition.xml
-
- - **/README - src/main/resources/** - **/LICENSE.txt - **.xml - assets/** - src/test/files/checks/htl/HtlCommentsCheck.html - -
- - - validate - - format - - - -
- - - org.apache.maven.plugins - maven-dependency-plugin - 3.0.0 - - - copy-dependencies - test-compile - - copy-dependencies - - - provided - ${project.build.directory}/test-jars - false - false - true - - - - -
-
+ + + + org.sonarsource.sonar-packaging-maven-plugin + sonar-packaging-maven-plugin + 1.23.0.740 + true + + ${project.name} + ${project.description} + aemrules + com.vml.aemrules.AemRulesSonarPlugin + 9.9 + https://github.com/wttech/AEM-Rules-for-SonarQube/issues + https://github.com/wttech/AEM-Rules-for-SonarQube/tree/${tagName} + https://github.com/wttech/AEM-Rules-for-SonarQube + true + true + java + + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + false + true + false + + + + package + + shade + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + 11 + + + + org.jacoco + jacoco-maven-plugin + 0.8.11 + + + prepare-agent + + prepare-agent + + + + + + com.github.hazendaz.maven + coveralls-maven-plugin + 4.5.0-M2 + + ${coveralls.repo.token} + + + + com.mycila + license-maven-plugin + 3.0 + + false +
${basedir}/assets/license-template.txt
+ +
${basedir}/assets/license-header-definition.xml
+
+ + **/README + src/main/resources/** + **/LICENSE.txt + **.xml + assets/** + src/test/files/htl/HtlCommentsCheck.html + +
+ + + validate + + format + + + +
+ + + org.apache.maven.plugins + maven-dependency-plugin + 3.0.0 + + + copy-dependencies + test-compile + + copy-dependencies + + + provided + ${project.build.directory}/test-jars + false + false + true + + + + + + org.apache.maven.plugins + maven-resources-plugin + 3.3.1 + + + copy-jar-to-local-docker-plugins + package + + copy-resources + + + ${basedir}/local-docker-image/extensions/plugins + + + ${basedir}/target + sonar-aemrules-plugin-${version}.jar + false + + + + + + +
+
diff --git a/src/main/java/com/cognifide/aemrules/AemRulesSonarPlugin.java b/src/main/java/com/cognifide/aemrules/AemRulesSonarPlugin.java deleted file mode 100644 index 69e4dbee..00000000 --- a/src/main/java/com/cognifide/aemrules/AemRulesSonarPlugin.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules; - -import com.cognifide.aemrules.extensions.AemRulesRulesDefinition; -import com.cognifide.aemrules.java.rules.JavaCheckClasses; -import com.cognifide.aemrules.htl.Htl; -import com.cognifide.aemrules.htl.Constants; -import com.cognifide.aemrules.htl.HtlProfile; -import com.cognifide.aemrules.htl.HtlSensor; -import org.sonar.api.Plugin; -import org.sonar.api.config.PropertyDefinition; -import org.sonar.api.resources.Qualifiers; - -import java.util.Arrays; -import java.util.List; - -public class AemRulesSonarPlugin implements Plugin { - - private static List pluginProperties() { - return Arrays.asList( - PropertyDefinition.builder(Constants.FILE_EXTENSIONS_PROP_KEY) - .name("File suffixes") - .description("List of file suffixes that will be scanned.") - .category(Htl.NAME) - .defaultValue(Constants.FILE_EXTENSIONS_DEF_VALUE) - .onQualifiers(Qualifiers.PROJECT) - .multiValues(true) - .build(), - PropertyDefinition.builder(Constants.HTL_FILES_RELATIVE_PATHS_KEY) - .name("HTL files relative paths") - .description("List of relative paths that contains HTL files.") - .category(Htl.NAME) - .defaultValue(Constants.HTL_FILES_RELATIVE_PATHS_DEF_VALUE) - .onQualifiers(Qualifiers.PROJECT) - .multiValues(true) - .build() - ); - } - - @Override - public void define(Context context) { - context.addExtensions( - Htl.class, - AemRulesRulesDefinition.class, - JavaCheckClasses.class, - HtlProfile.class, - HtlSensor.class); - context.addExtensions(pluginProperties()); - } -} diff --git a/src/main/java/com/cognifide/aemrules/extensions/AemRulesRulesDefinition.java b/src/main/java/com/cognifide/aemrules/extensions/AemRulesRulesDefinition.java deleted file mode 100644 index 1d516103..00000000 --- a/src/main/java/com/cognifide/aemrules/extensions/AemRulesRulesDefinition.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.extensions; - -import com.cognifide.aemrules.htl.Htl; -import com.cognifide.aemrules.htl.rules.HtlCheckClasses; -import com.cognifide.aemrules.java.rules.JavaCheckClasses; -import org.sonar.api.server.rule.RulesDefinition; - -public class AemRulesRulesDefinition implements RulesDefinition { - - private static final RulesLoader rulesLoader = new RulesLoader(); - - @Override - public void define(Context context) { - defineJavaRepository(context); - defineHtlRepository(context); - } - - private void defineHtlRepository(Context context) { - NewRepository repo = context - .createRepository(HtlCheckClasses.REPOSITORY_KEY, Htl.KEY) - .setName(HtlCheckClasses.REPOSITORY_NAME); - rulesLoader.load(repo, HtlCheckClasses.getCheckClasses()); - repo.done(); - } - - private void defineJavaRepository(Context context) { - NewRepository repo = context - .createRepository(JavaCheckClasses.REPOSITORY_KEY, "java") - .setName(JavaCheckClasses.REPOSITORY_NAME); - rulesLoader.load(repo, JavaCheckClasses.CHECK_CLASSES); - repo.done(); - - } - -} diff --git a/src/main/java/com/cognifide/aemrules/extensions/RulesLoader.java b/src/main/java/com/cognifide/aemrules/extensions/RulesLoader.java deleted file mode 100644 index 25c18848..00000000 --- a/src/main/java/com/cognifide/aemrules/extensions/RulesLoader.java +++ /dev/null @@ -1,154 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.extensions; - -import com.cognifide.aemrules.metadata.Metadata; -import java.io.IOException; -import java.lang.reflect.Field; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.AbstractMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.annotation.CheckForNull; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.rule.RuleStatus; -import org.sonar.api.server.rule.RuleParamType; -import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.api.server.rule.RulesDefinition.DebtRemediationFunctions; -import org.sonar.api.utils.AnnotationUtils; -import org.sonar.api.utils.FieldUtils2; -import org.sonar.check.Rule; -import org.sonar.check.RuleProperty; - - -public class RulesLoader { - - private static final Logger LOG = LoggerFactory.getLogger(RulesLoader.class); - - private static final String RULE_DESCRIPTION_FOLDER = "rules"; - - private static final String RULE_DESCRIPTION_EXTENSION = "md"; - - private static final Map, RuleParamType> TYPE_FOR_CLASS = Stream.of( - new AbstractMap.SimpleImmutableEntry<>(Integer.class, RuleParamType.INTEGER), - new AbstractMap.SimpleImmutableEntry<>(int.class, RuleParamType.INTEGER), - new AbstractMap.SimpleImmutableEntry<>(Float.class, RuleParamType.FLOAT), - new AbstractMap.SimpleImmutableEntry<>(float.class, RuleParamType.FLOAT), - new AbstractMap.SimpleImmutableEntry<>(Boolean.class, RuleParamType.BOOLEAN), - new AbstractMap.SimpleImmutableEntry<>(boolean.class, RuleParamType.BOOLEAN) - ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - - private static RuleParamType guessType(Class type) { - return TYPE_FOR_CLASS.getOrDefault(type, RuleParamType.STRING); - } - - public void load(RulesDefinition.NewExtendedRepository repo, List> annotatedClasses) { - for (Class annotatedClass : annotatedClasses) { - loadRule(repo, annotatedClass); - } - } - - @CheckForNull - private RulesDefinition.NewRule loadRule(RulesDefinition.NewExtendedRepository repo, Class clazz) { - return Optional.ofNullable(AnnotationUtils.getAnnotation(clazz, Rule.class)) - .map(annotationRule -> createRule(repo, clazz, annotationRule)) - .orElse(null); - } - - private RulesDefinition.NewRule createRule(RulesDefinition.NewExtendedRepository repo, Class clazz, Rule ruleAnnotation) { - String ruleKey = StringUtils.defaultIfEmpty(ruleAnnotation.key(), clazz.getCanonicalName()); - String ruleName = StringUtils.defaultIfEmpty(ruleAnnotation.name(), null); - String description = StringUtils.defaultIfEmpty(loadDescription(ruleKey), "No description yet."); - - RulesDefinition.NewRule rule = repo.createRule(ruleKey); - rule.setName(ruleName).setMarkdownDescription(description); - rule.setSeverity(ruleAnnotation.priority().name()); - rule.setStatus(RuleStatus.valueOf(ruleAnnotation.status())); - rule.setTags(ruleAnnotation.tags()); - - setMetadata(rule, clazz); - - List fields = FieldUtils2.getFields(clazz, true); - for (Field field : fields) { - loadParameters(rule, field); - } - - return rule; - } - - private void setMetadata(RulesDefinition.NewRule rule, Class clazz) { - Optional.ofNullable(AnnotationUtils.getAnnotation(clazz, Metadata.class)) - .ifPresent(metadataAnnotation -> setTechnicalDebt(rule, metadataAnnotation)); - } - - private void setTechnicalDebt(RulesDefinition.NewRule rule, Metadata metadataAnnotation) { - String technicalDebt = metadataAnnotation.technicalDebt(); - if (StringUtils.isNotEmpty(technicalDebt)) { - DebtRemediationFunctions remediationFunction = rule.debtRemediationFunctions(); - rule.setDebtRemediationFunction(remediationFunction.constantPerIssue(technicalDebt)); - } - } - - private String loadDescription(String ruleKey) { - return loadResource(RULE_DESCRIPTION_FOLDER, ruleKey, RULE_DESCRIPTION_EXTENSION); - } - - private String loadResource(String resourceFolder, String ruleKey, String fileExtension) { - String result = null; - try { - String path = String.format("/%s/%s.%s", resourceFolder, ruleKey, fileExtension); - URL url = getClass().getResource(path); - result = IOUtils.toString(url, StandardCharsets.UTF_8); - } catch (IOException | IllegalArgumentException e) { - LOG.error("Cannot read resource file.", e); - } - return result; - } - - private void loadParameters(RulesDefinition.NewRule rule, Field field) { - RuleProperty propertyAnnotation = field.getAnnotation(RuleProperty.class); - if (propertyAnnotation != null) { - String fieldKey = StringUtils.defaultIfEmpty(propertyAnnotation.key(), field.getName()); - RulesDefinition.NewParam param = rule.createParam(fieldKey) - .setDescription(propertyAnnotation.description()) - .setDefaultValue(propertyAnnotation.defaultValue()); - - if (!StringUtils.isBlank(propertyAnnotation.type())) { - try { - param.setType(RuleParamType.parse(propertyAnnotation.type().trim())); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Invalid property type [" + propertyAnnotation.type() + "]", e); - } - } else { - param.setType(guessType(field.getType())); - } - } - } - -} diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/ExplicitNamesInLoopsCheck.java b/src/main/java/com/cognifide/aemrules/htl/checks/ExplicitNamesInLoopsCheck.java deleted file mode 100644 index 06949668..00000000 --- a/src/main/java/com/cognifide/aemrules/htl/checks/ExplicitNamesInLoopsCheck.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import org.sonar.check.Priority; -import org.sonar.check.Rule; -import org.sonar.plugins.html.node.TagNode; - -@Rule( - key = ExplicitNamesInLoopsCheck.RULE_KEY, - name = ExplicitNamesInLoopsCheck.RULE_NAME, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - all = true -) -@Metadata( - technicalDebt = "10min" -) -public class ExplicitNamesInLoopsCheck extends AbstractHtlCheck { - - static final String RULE_KEY = "HTL-3"; - - static final String RULE_NAME = "Explicit names in loops"; - - static final String RULE_MESSAGE = "Use explicit names in loops"; - - @Override - public void startElement(TagNode node) { - if (isSlyList(node) || isSlyRepeat(node)) { - createViolation(node.getStartLinePosition(), RULE_MESSAGE); - } - } - - private boolean isSlyList(TagNode node) { - return node.getAttributes().stream() - .anyMatch(attribute -> "data-sly-list".equals(attribute.getName())); - } - - private boolean isSlyRepeat(TagNode node) { - return node.getAttributes().stream() - .anyMatch(attribute -> "data-sly-repeat".equals(attribute.getName())); - } -} \ No newline at end of file diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/HtlCommentsCheck.java b/src/main/java/com/cognifide/aemrules/htl/checks/HtlCommentsCheck.java deleted file mode 100644 index 99f93a4a..00000000 --- a/src/main/java/com/cognifide/aemrules/htl/checks/HtlCommentsCheck.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import org.apache.commons.lang3.StringUtils; -import org.apache.sling.scripting.sightly.impl.compiler.Syntax; -import org.sonar.check.Priority; -import org.sonar.check.Rule; -import org.sonar.plugins.html.node.CommentNode; - -@Rule( - key = HtlCommentsCheck.RULE_KEY, - name = HtlCommentsCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - all = true -) -@Metadata( - technicalDebt = "5min" -) -public class HtlCommentsCheck extends AbstractHtlCheck { - - static final String RULE_KEY = "HTL-5"; - - static final String RULE_MESSAGE = "Always use HTL style of comments"; - - private static final List SSI_ELEMENTS = Arrays.asList("comment", "config", "echo", "exec", "fsize", "flastmod", - "include", "printenv", "set"); - - private static final Pattern CONDITIONAL_COMMENT_PATTERN = Pattern - .compile(""); - - private static final Pattern ESI_COMMENT_PATTERN = Pattern - .compile(""); - - private static final List EXCEPTIONS = buildExceptionList(); - - @Override - public void comment(CommentNode node) { - String code = StringUtils.deleteWhitespace(node.getCode()); - if (!Syntax.isSightlyComment(code) && !isException(code)) { - createViolation(node.getStartLinePosition(), RULE_MESSAGE); - } - } - - private boolean isException(String code) { - return EXCEPTIONS.stream() - .map(pattern -> pattern.matcher(code)) - .anyMatch(Matcher::matches); - } - - private static List buildExceptionList() { - List result = new ArrayList<>(); - result.add(CONDITIONAL_COMMENT_PATTERN); - result.add(ESI_COMMENT_PATTERN); - result.addAll(buildSsiRegex(SSI_ELEMENTS)); - - return result; - } - - private static List buildSsiRegex(List elements) { - return elements.stream() - .map(e -> "") - .map(Pattern::compile) - .collect(Collectors.toList()); - } -} \ No newline at end of file diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/ParsingErrorCheck.java b/src/main/java/com/cognifide/aemrules/htl/checks/ParsingErrorCheck.java deleted file mode 100644 index f3b9851d..00000000 --- a/src/main/java/com/cognifide/aemrules/htl/checks/ParsingErrorCheck.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.htl.api.ParsingErrorRule; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import org.sonar.check.Priority; -import org.sonar.check.Rule; - -@Rule( - key = ParsingErrorCheck.RULE_KEY, - name = ParsingErrorCheck.RULE_NAME, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "5min" -) -@ParsingErrorRule -public class ParsingErrorCheck extends AbstractHtlCheck { - - static final String RULE_KEY = "HTL-0"; - - static final String RULE_NAME = "Compilation error"; -} diff --git a/src/main/java/com/cognifide/aemrules/htl/rules/HtlCheckClasses.java b/src/main/java/com/cognifide/aemrules/htl/rules/HtlCheckClasses.java deleted file mode 100644 index 67f0bd4f..00000000 --- a/src/main/java/com/cognifide/aemrules/htl/rules/HtlCheckClasses.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.htl.rules; - -import com.cognifide.aemrules.htl.Htl; -import com.cognifide.aemrules.htl.api.HtlCheck; -import com.cognifide.aemrules.htl.checks.AvoidExtraSlyTagsCheck; -import com.cognifide.aemrules.htl.checks.AvoidUsingUnsafeDisplayContextCheck; -import com.cognifide.aemrules.htl.checks.CamelCaseCheck; -import com.cognifide.aemrules.htl.checks.DefaultDisplayContextCheck; -import com.cognifide.aemrules.htl.checks.DisplayContextInConditionalCommentsCheck; -import com.cognifide.aemrules.htl.checks.EventMandatoryDisplayContextCheck; -import com.cognifide.aemrules.htl.checks.ExplicitNamesInLoopsCheck; -import com.cognifide.aemrules.htl.checks.HtlAttributesShouldBeAtTheEndCheck; -import com.cognifide.aemrules.htl.checks.HtlCommentsCheck; -import com.cognifide.aemrules.htl.checks.InlineStyleMandatoryDisplayContextCheck; -import com.cognifide.aemrules.htl.checks.NamingAndReusingConditionsCheck; -import com.cognifide.aemrules.htl.checks.ParsingErrorCheck; -import com.cognifide.aemrules.htl.checks.PlaceTemplatesInSeparateFilesCheck; -import com.cognifide.aemrules.htl.checks.ScriptsAndStyleMandatoryDisplayContextCheck; -import com.cognifide.aemrules.htl.checks.SlyElementsAreAutomaticallyUnwrappedCheck; -import com.cognifide.aemrules.htl.checks.UseMostRestrictiveHtlContextCheck; -import com.cognifide.aemrules.htl.checks.UseSlyTagsOverRedundantMarkupCheck; -import org.sonar.check.Rule; - -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -public final class HtlCheckClasses { - - public static final String REPOSITORY_KEY = Htl.KEY; - - public static final String REPOSITORY_NAME = "AEM Rules"; - - private static final List> CLASSES = Arrays.asList( - ParsingErrorCheck.class, - HtlCommentsCheck.class, - AvoidExtraSlyTagsCheck.class, - AvoidUsingUnsafeDisplayContextCheck.class, - DefaultDisplayContextCheck.class, - DisplayContextInConditionalCommentsCheck.class, - EventMandatoryDisplayContextCheck.class, - HtlAttributesShouldBeAtTheEndCheck.class, - InlineStyleMandatoryDisplayContextCheck.class, - NamingAndReusingConditionsCheck.class, - PlaceTemplatesInSeparateFilesCheck.class, - ScriptsAndStyleMandatoryDisplayContextCheck.class, - UseMostRestrictiveHtlContextCheck.class, - UseSlyTagsOverRedundantMarkupCheck.class, - CamelCaseCheck.class, - SlyElementsAreAutomaticallyUnwrappedCheck.class, - ExplicitNamesInLoopsCheck.class - ); - - private HtlCheckClasses() { - //private constructor - } - - public static List> getCheckClasses() { - return CLASSES; - } - - public static Rule getRule(Class clazz) { - return Optional.ofNullable(clazz) - .filter(c -> c.isAnnotationPresent(Rule.class)) - .map(c -> c.getAnnotation(Rule.class)) - .orElse(null); - } -} diff --git a/src/main/java/com/cognifide/aemrules/java/checks/resourceresolver/close/ResourceResolverTryWithResourcesCheck.java b/src/main/java/com/cognifide/aemrules/java/checks/resourceresolver/close/ResourceResolverTryWithResourcesCheck.java deleted file mode 100644 index a745716a..00000000 --- a/src/main/java/com/cognifide/aemrules/java/checks/resourceresolver/close/ResourceResolverTryWithResourcesCheck.java +++ /dev/null @@ -1,129 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.java.checks.resourceresolver.close; - -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import java.util.ArrayList; -import java.util.List; -import org.sonar.check.Priority; -import org.sonar.check.Rule; -import org.sonar.java.model.declaration.VariableTreeImpl; -import org.sonar.plugins.java.api.JavaFileScanner; -import org.sonar.plugins.java.api.JavaFileScannerContext; -import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; -import org.sonar.plugins.java.api.tree.BaseTreeVisitor; -import org.sonar.plugins.java.api.tree.LambdaExpressionTree; -import org.sonar.plugins.java.api.tree.TryStatementTree; -import org.sonar.plugins.java.api.tree.VariableTree; - -@Rule( - key = ResourceResolverTryWithResourcesCheck.RULE_KEY, - name = ResourceResolverTryWithResourcesCheck.RULE_MESSAGE, - priority = Priority.INFO, - tags = Tags.AEM -) -@AemVersion( - all = true -) -@Metadata( - technicalDebt = "10min" -) - -public class ResourceResolverTryWithResourcesCheck extends BaseTreeVisitor implements - JavaFileScanner { - - public static final String RULE_KEY = "AEM-20"; - - protected static final String RULE_MESSAGE = "ResourceResolver can be closed using try-with-resources Java 7 feature."; - - private static final String SLING_RESOURCE_RESOLVER = "org.apache.sling.api.resource.ResourceResolver"; - - private boolean insideTryStatement = false; - - private boolean insideLambdaExpression = false; - - private JavaFileScannerContext context; - - private List resourceResolversInTryWithResources = new ArrayList<>(); - - public void scanFile(JavaFileScannerContext javaFileScannerContext) { - context = javaFileScannerContext; - scan(context.getTree()); - } - - @Override - public void visitVariable(VariableTree tree) { - if (isResourceResolverUsedProperly(tree)) { - context.reportIssue(this, tree, RULE_MESSAGE); - } - super.visitVariable(tree); - } - - @Override - public void visitAssignmentExpression(AssignmentExpressionTree tree) { - if (insideTryStatement && !insideLambdaExpression && isResourceResolver(tree)) { - context.reportIssue(this, tree, RULE_MESSAGE); - } - super.visitAssignmentExpression(tree); - } - - @Override - public void visitTryStatement(TryStatementTree tree) { - insideTryStatement = true; - tree.resourceList().stream() - // We're iterating over a resource specification in a try-with-resource block - // so we expect variable trees - .filter(resource -> resource instanceof VariableTree) - .map(VariableTree.class::cast) - .map(resource -> resource.simpleName().name()) - .forEach(resourceResolversInTryWithResources::add); - - super.visitTryStatement(tree); - resourceResolversInTryWithResources.clear(); - insideTryStatement = false; - } - - @Override - public void visitLambdaExpression(LambdaExpressionTree lambdaExpressionTree) { - insideLambdaExpression = true; - super.visitLambdaExpression(lambdaExpressionTree); - insideLambdaExpression = false; - } - - private boolean isResourceResolverUsedProperly(VariableTree tree) { - return insideTryStatement && !insideLambdaExpression && isResourceResolver(tree) - && !resourceResolversInTryWithResources - .contains(getResourceResolver(tree)); - } - - private boolean isResourceResolver(AssignmentExpressionTree tree) { - return SLING_RESOURCE_RESOLVER.equals(tree.variable().symbolType().fullyQualifiedName()); - } - - private boolean isResourceResolver(VariableTree tree) { - return SLING_RESOURCE_RESOLVER.equals(tree.type().symbolType().fullyQualifiedName()); - } - - private String getResourceResolver(VariableTree tree) { - return tree.simpleName().name(); - } -} diff --git a/src/main/java/com/cognifide/aemrules/java/rules/JavaCheckClasses.java b/src/main/java/com/cognifide/aemrules/java/rules/JavaCheckClasses.java deleted file mode 100644 index 9d810fd2..00000000 --- a/src/main/java/com/cognifide/aemrules/java/rules/JavaCheckClasses.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.java.rules; - -import com.cognifide.aemrules.java.checks.AdministrativeAccessUsageCheck; -import com.cognifide.aemrules.java.checks.AnnotationsConstantsCheck; -import com.cognifide.aemrules.java.checks.ConstantsCheck; -import com.cognifide.aemrules.java.checks.ContentResourceShouldBeNullCheckedCheck; -import com.cognifide.aemrules.java.checks.ModifiableValueMapUsageCheck; -import com.cognifide.aemrules.java.checks.PreferSlingServletAnnotation; -import com.cognifide.aemrules.java.checks.SessionShouldBeLoggedOut; -import com.cognifide.aemrules.java.checks.SynchronizedKeywordUsageCheck; -import com.cognifide.aemrules.java.checks.ThreadSafeFieldCheck; -import com.cognifide.aemrules.java.checks.resourceresolver.close.ResourceResolverShouldBeClosed; -import com.cognifide.aemrules.java.checks.resourceresolver.close.ResourceResolverTryWithResourcesCheck; -import com.cognifide.aemrules.java.checks.slingmodels.DefaultInjectionStrategyAnnotationCheck; -import com.cognifide.aemrules.java.checks.slingquery.SlingQueryImplicitStrategyCheck; -import com.cognifide.aemrules.version.AemVersion; -import com.cognifide.aemrules.version.VersionSupportChecker; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; -import org.sonar.api.config.Configuration; -import org.sonar.plugins.java.api.CheckRegistrar; -import org.sonar.plugins.java.api.JavaCheck; - -public class JavaCheckClasses implements CheckRegistrar { - - public static final String REPOSITORY_KEY = "AEM Rules"; - - public static final String REPOSITORY_NAME = "AEM Rules"; - - public static final List> CHECK_CLASSES = Arrays.asList( - AdministrativeAccessUsageCheck.class, - AnnotationsConstantsCheck.class, - ConstantsCheck.class, - PreferSlingServletAnnotation.class, - ResourceResolverShouldBeClosed.class, - SessionShouldBeLoggedOut.class, - SynchronizedKeywordUsageCheck.class, - ThreadSafeFieldCheck.class, - DefaultInjectionStrategyAnnotationCheck.class, - ModifiableValueMapUsageCheck.class, - ContentResourceShouldBeNullCheckedCheck.class, - SlingQueryImplicitStrategyCheck.class, - ResourceResolverTryWithResourcesCheck.class - ); - - private final Configuration configuration; - - public JavaCheckClasses(Configuration configuration) { - this.configuration = configuration; - } - - @Override - public void register(RegistrarContext registrarContext) { - String aemVersion = configuration.get(VersionSupportChecker.VERSION_PROPERTY) - .orElse(VersionSupportChecker.DEFAULT_AEM_VERSION); - List> checkClassesToRegister = CHECK_CLASSES.stream() - .filter(checkClass -> shouldRegister(aemVersion, checkClass)) - .collect(Collectors.toList()); - registrarContext.registerClassesForRepository(REPOSITORY_KEY, checkClassesToRegister, - Collections.emptyList()); - } - - private boolean shouldRegister(String aemVersion, Class checkClass) { - return Optional.ofNullable(checkClass.getAnnotation(AemVersion.class)) - .map(supportedVersion -> VersionSupportChecker.create(supportedVersion).supports(aemVersion)) - .orElse(true); - } -} diff --git a/src/main/java/com/cognifide/aemrules/metadata/Metadata.java b/src/main/java/com/cognifide/aemrules/metadata/Metadata.java deleted file mode 100644 index 1c644a28..00000000 --- a/src/main/java/com/cognifide/aemrules/metadata/Metadata.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.metadata; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface Metadata { - - /** - * Sets a technical debt for the Rule. - */ - String technicalDebt(); -} diff --git a/src/main/java/com/cognifide/aemrules/tag/Tags.java b/src/main/java/com/cognifide/aemrules/tag/Tags.java deleted file mode 100644 index bcd0f8b8..00000000 --- a/src/main/java/com/cognifide/aemrules/tag/Tags.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.tag; - -public class Tags { - - public static final String AEM = "aem"; - - public static final String BUG = "bug"; - - public static final String PERFORMANCE = "performance"; - - public static final String MULTI_THREADING = "multi-threading"; - - public static final String SLING_MODELS = "sling-models"; - - private Tags() { - throw new AssertionError(); - } -} diff --git a/src/main/java/com/vml/aemrules/AemRulesSonarPlugin.java b/src/main/java/com/vml/aemrules/AemRulesSonarPlugin.java new file mode 100644 index 00000000..55dc5c07 --- /dev/null +++ b/src/main/java/com/vml/aemrules/AemRulesSonarPlugin.java @@ -0,0 +1,74 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules; + +import com.vml.aemrules.htl.Constants; +import com.vml.aemrules.htl.Htl; +import com.vml.aemrules.htl.HtlProfile; +import com.vml.aemrules.htl.HtlSensor; +import com.vml.aemrules.htl.rules.HtlRulesDefinition; +import com.vml.aemrules.java.rules.JavaCheckRegistrar; +import com.vml.aemrules.java.rules.JavaRulesDefinition; +import org.sonar.api.Plugin; +import org.sonar.api.config.PropertyDefinition; +import org.sonar.api.resources.Qualifiers; + +import java.util.Arrays; +import java.util.List; + +public class AemRulesSonarPlugin implements Plugin { + + private static List createHtlLanguageProperties() { + return Arrays.asList( + PropertyDefinition.builder(Constants.FILE_EXTENSIONS_PROP_KEY) + .name("File suffixes") + .description("List of file suffixes that will be scanned.") + .category(Htl.LANGUAGE_NAME) + .defaultValue(Constants.FILE_EXTENSIONS_DEF_VALUE) + .onQualifiers(Qualifiers.PROJECT) + .multiValues(true) + .build(), + PropertyDefinition.builder(Constants.HTL_FILES_RELATIVE_PATHS_KEY) + .name("HTL files relative paths") + .description("List of relative paths that contains HTL files.") + .category(Htl.LANGUAGE_NAME) + .defaultValue(Constants.HTL_FILES_RELATIVE_PATHS_DEF_VALUE) + .onQualifiers(Qualifiers.PROJECT) + .multiValues(true) + .build() + ); + } + + @Override + public void define(Context context) { + context.addExtensions( + JavaRulesDefinition.class, + JavaCheckRegistrar.class + ); + + context.addExtensions( + Htl.class, + HtlRulesDefinition.class, + HtlProfile.class, + HtlSensor.class); + + context.addExtensions(createHtlLanguageProperties()); + } +} diff --git a/src/main/java/com/vml/aemrules/htl/AnalysisException.java b/src/main/java/com/vml/aemrules/htl/AnalysisException.java new file mode 100644 index 00000000..374a2443 --- /dev/null +++ b/src/main/java/com/vml/aemrules/htl/AnalysisException.java @@ -0,0 +1,32 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl; + +public class AnalysisException extends RuntimeException { + + public AnalysisException(String message) { + super(message); + } + + public AnalysisException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/com/cognifide/aemrules/htl/Constants.java b/src/main/java/com/vml/aemrules/htl/Constants.java similarity index 85% rename from src/main/java/com/cognifide/aemrules/htl/Constants.java rename to src/main/java/com/vml/aemrules/htl/Constants.java index 517f0de9..0944607f 100644 --- a/src/main/java/com/cognifide/aemrules/htl/Constants.java +++ b/src/main/java/com/vml/aemrules/htl/Constants.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,20 +17,20 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; public final class Constants { - private Constants() { - //private constructor - } + public static final String REPOSITORY_KEY = "AEM-HTL"; + public static final String REPOSITORY_NAME = "AEM HTL"; public static final String FILE_EXTENSIONS_PROP_KEY = "sonar.htl.file.suffixes"; - public static final String FILE_EXTENSIONS_DEF_VALUE = ".html"; - public static final String HTL_FILES_RELATIVE_PATHS_KEY = "sonar.htl.file.paths"; - public static final String HTL_FILES_RELATIVE_PATHS_DEF_VALUE = "src/main/content/jcr_root"; + private Constants() { + //private constructor + } + } diff --git a/src/main/java/com/cognifide/aemrules/htl/Htl.java b/src/main/java/com/vml/aemrules/htl/Htl.java similarity index 83% rename from src/main/java/com/cognifide/aemrules/htl/Htl.java rename to src/main/java/com/vml/aemrules/htl/Htl.java index 369fadf7..d8597279 100644 --- a/src/main/java/com/cognifide/aemrules/htl/Htl.java +++ b/src/main/java/com/vml/aemrules/htl/Htl.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; import org.sonar.api.resources.AbstractLanguage; @@ -26,12 +26,12 @@ public class Htl extends AbstractLanguage { /** * Language key */ - public static final String KEY = "htl"; + public static final String LANGUAGE_KEY = "htl"; /** * Language name */ - public static final String NAME = "HTL"; + public static final String LANGUAGE_NAME = "HTL"; /** * Default Htl files known suffixes @@ -39,7 +39,7 @@ public class Htl extends AbstractLanguage { public static final String[] DEFAULT_FILE_SUFFIXES = new String[]{}; public Htl() { - super(KEY, NAME); + super(LANGUAGE_KEY, LANGUAGE_NAME); } @Override diff --git a/src/main/java/com/cognifide/aemrules/htl/HtlChecks.java b/src/main/java/com/vml/aemrules/htl/HtlChecks.java similarity index 84% rename from src/main/java/com/cognifide/aemrules/htl/HtlChecks.java rename to src/main/java/com/vml/aemrules/htl/HtlChecks.java index f5963d9d..9851a759 100644 --- a/src/main/java/com/cognifide/aemrules/htl/HtlChecks.java +++ b/src/main/java/com/vml/aemrules/htl/HtlChecks.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,18 +17,19 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; -import com.cognifide.aemrules.htl.api.HtlCheck; +import com.vml.aemrules.htl.api.HtlCheck; +import org.sonar.api.batch.rule.CheckFactory; +import org.sonar.api.batch.rule.Checks; +import org.sonar.api.rule.RuleKey; + +import javax.annotation.Nullable; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; -import javax.annotation.Nullable; -import org.sonar.api.batch.rule.CheckFactory; -import org.sonar.api.batch.rule.Checks; -import org.sonar.api.rule.RuleKey; public class HtlChecks { @@ -46,8 +47,8 @@ public static HtlChecks createHtlCheck(CheckFactory checkFactory) { public HtlChecks addChecks(String repositoryKey, Iterable> checkClass) { Checks htlChecks = checkFactory - .create(repositoryKey) - .addAnnotatedChecks(checkClass); + .create(repositoryKey) + .addAnnotatedChecks(checkClass); checksByRepository.add(htlChecks); return this; } @@ -68,8 +69,8 @@ public RuleKey ruleKeyFor(HtlCheck check) { public List getAll() { return checksByRepository.stream() - .map(Checks::all) - .flatMap(Collection::stream) - .collect(Collectors.toList()); + .map(Checks::all) + .flatMap(Collection::stream) + .collect(Collectors.toList()); } } diff --git a/src/main/java/com/cognifide/aemrules/htl/HtlFilePredicateProvider.java b/src/main/java/com/vml/aemrules/htl/HtlFilePredicateProvider.java similarity index 94% rename from src/main/java/com/cognifide/aemrules/htl/HtlFilePredicateProvider.java rename to src/main/java/com/vml/aemrules/htl/HtlFilePredicateProvider.java index 5173d77b..3a0d84c5 100644 --- a/src/main/java/com/cognifide/aemrules/htl/HtlFilePredicateProvider.java +++ b/src/main/java/com/vml/aemrules/htl/HtlFilePredicateProvider.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; import org.apache.commons.lang3.StringUtils; import org.sonar.api.batch.fs.FilePredicate; @@ -46,7 +46,7 @@ public static FilePredicate createFilePredicate(Configuration configuration, Sen return predicates.and( predicates.hasType(InputFile.Type.MAIN), predicates.or( - predicates.hasLanguages(Htl.KEY), + predicates.hasLanguages(Htl.LANGUAGE_KEY), predicates.or(fileExtensions) ), predicates.or(relativePaths) diff --git a/src/main/java/com/cognifide/aemrules/htl/HtlFilesAnalyzer.java b/src/main/java/com/vml/aemrules/htl/HtlFilesAnalyzer.java similarity index 73% rename from src/main/java/com/cognifide/aemrules/htl/HtlFilesAnalyzer.java rename to src/main/java/com/vml/aemrules/htl/HtlFilesAnalyzer.java index c4f423e8..2ca8c566 100644 --- a/src/main/java/com/cognifide/aemrules/htl/HtlFilesAnalyzer.java +++ b/src/main/java/com/vml/aemrules/htl/HtlFilesAnalyzer.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,45 +17,47 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; -import com.cognifide.aemrules.htl.api.ParsingErrorRule; -import com.cognifide.aemrules.htl.rules.HtlCheckClasses; -import java.io.IOException; -import java.io.InterruptedIOException; -import java.util.concurrent.CancellationException; - -import com.cognifide.aemrules.utils.Throwables; +import com.vml.aemrules.htl.api.ParsingErrorRule; +import com.vml.aemrules.htl.rules.HtlRulesList; +import com.vml.aemrules.utils.Throwables; import org.apache.sling.scripting.sightly.compiler.SightlyCompilerException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.rule.CheckFactory; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.issue.NewIssue; import org.sonar.api.batch.sensor.issue.NewIssueLocation; import org.sonar.api.rule.RuleKey; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.squidbridge.ProgressReport; -import org.sonar.squidbridge.api.AnalysisException; +import org.sonarsource.analyzer.commons.ProgressReport; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.util.concurrent.CancellationException; + +import static com.vml.aemrules.htl.Constants.REPOSITORY_KEY; + public abstract class HtlFilesAnalyzer { - private static final Logger LOGGER = Loggers.get(HtlFilesAnalyzer.class); + private static final Logger LOGGER = LoggerFactory.getLogger(HtlFilesAnalyzer.class); protected final HtlChecks checks; private final RuleKey parsingErrorRuleKey; - public HtlFilesAnalyzer(CheckFactory checkFactory) { + protected HtlFilesAnalyzer(CheckFactory checkFactory) { this.checks = HtlChecks.createHtlCheck(checkFactory) - .addChecks(HtlCheckClasses.REPOSITORY_KEY, HtlCheckClasses.getCheckClasses()); + .addChecks(REPOSITORY_KEY, HtlRulesList.getChecks()); this.parsingErrorRuleKey = setupParsingErrorRuleKey(checks); } private static RuleKey setupParsingErrorRuleKey(HtlChecks checks) { return checks.getAll().stream() - .filter(check -> check.getClass().isAnnotationPresent(ParsingErrorRule.class)) - .findFirst() - .map(checks::ruleKeyFor) - .orElse(null); + .filter(check -> check.getClass().isAnnotationPresent(ParsingErrorRule.class)) + .findFirst() + .map(checks::ruleKeyFor) + .orElse(null); } private static void stopProgressReport(ProgressReport progressReport, boolean success) { @@ -75,9 +77,9 @@ private static void checkInterrupted(Exception e) { private static void processException(Exception e, SensorContext sensorContext, InputFile inputFile) { sensorContext.newAnalysisError() - .onFile(inputFile) - .message(e.getMessage()) - .save(); + .onFile(inputFile) + .message(e.getMessage()) + .save(); } public void analyseFiles(SensorContext context, Iterable inputFiles, ProgressReport progressReport) { @@ -86,7 +88,7 @@ public void analyseFiles(SensorContext context, Iterable inputFiles, for (InputFile inputFile : inputFiles) { if (context.isCancelled()) { throw new CancellationException( - "Analysis interrupted because the SensorContext is in cancelled state"); + "Analysis interrupted because the SensorContext is in cancelled state"); } analyse(context, inputFile); progressReport.nextFile(); @@ -107,7 +109,7 @@ private void analyse(SensorContext sensorContext, InputFile inputFile) { scanFile(sensorContext, inputFile); } catch (SightlyCompilerException e) { checkInterrupted(e); - LOGGER.error("Unable to parse file: " + inputFile.uri()); + LOGGER.error("Unable to parse file: {}", inputFile.uri()); LOGGER.error(e.getMessage()); processRecognitionException(e, sensorContext, inputFile); } catch (Exception e) { @@ -125,24 +127,24 @@ private void processRecognitionException(SightlyCompilerException e, SensorConte int lineOffset = 0; sensorContext.newAnalysisError() - .onFile(inputFile) - .at(inputFile.newPointer(e.getLine(), lineOffset)) - .message(e.getMessage()) - .save(); + .onFile(inputFile) + .at(inputFile.newPointer(e.getLine(), lineOffset)) + .message(e.getMessage()) + .save(); } private void processRecognitionExceptionForCustomRule(SightlyCompilerException e, SensorContext sensorContext, InputFile inputFile) { NewIssue newIssue = sensorContext.newIssue(); NewIssueLocation primaryLocation = newIssue.newLocation() - .message("Parse error: " + e.getMessage()) - .on(inputFile) - .at(inputFile.selectLine(e.getLine())); + .message("Parse error: " + e.getMessage()) + .on(inputFile) + .at(inputFile.selectLine(e.getLine())); newIssue - .forRule(parsingErrorRuleKey) - .at(primaryLocation) - .save(); + .forRule(parsingErrorRuleKey) + .at(primaryLocation) + .save(); } } diff --git a/src/main/java/com/cognifide/aemrules/htl/HtlProfile.java b/src/main/java/com/vml/aemrules/htl/HtlProfile.java similarity index 62% rename from src/main/java/com/cognifide/aemrules/htl/HtlProfile.java rename to src/main/java/com/vml/aemrules/htl/HtlProfile.java index 73110c8d..afc50dfa 100644 --- a/src/main/java/com/cognifide/aemrules/htl/HtlProfile.java +++ b/src/main/java/com/vml/aemrules/htl/HtlProfile.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,26 +17,29 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; -import com.cognifide.aemrules.htl.rules.HtlCheckClasses; -import java.util.Objects; +import com.vml.aemrules.htl.rules.HtlRulesList; import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition; import org.sonar.check.Rule; +import java.util.Objects; + +import static com.vml.aemrules.htl.Constants.REPOSITORY_KEY; + public class HtlProfile implements BuiltInQualityProfilesDefinition { - private static final String QUALITY_PROFILE_NAME = "AEM HTL Profile"; + private static final String QUALITY_PROFILE_NAME = "HTL"; @Override public void define(Context context) { NewBuiltInQualityProfile htl = context - .createBuiltInQualityProfile(QUALITY_PROFILE_NAME, Htl.KEY); - HtlCheckClasses.getCheckClasses().stream() - .map(HtlCheckClasses::getRule) - .map(Rule::key) - .filter(Objects::nonNull) - .forEach(ruleKey -> htl.activateRule(HtlCheckClasses.REPOSITORY_KEY, ruleKey)); + .createBuiltInQualityProfile(QUALITY_PROFILE_NAME, Htl.LANGUAGE_KEY); + HtlRulesList.getChecks().stream() + .map(HtlRulesList::getRule) + .map(Rule::key) + .filter(Objects::nonNull) + .forEach(ruleKey -> htl.activateRule(REPOSITORY_KEY, ruleKey)); htl.done(); } } diff --git a/src/main/java/com/cognifide/aemrules/htl/HtlSensor.java b/src/main/java/com/vml/aemrules/htl/HtlSensor.java similarity index 83% rename from src/main/java/com/cognifide/aemrules/htl/HtlSensor.java rename to src/main/java/com/vml/aemrules/htl/HtlSensor.java index b63ab900..5086a058 100644 --- a/src/main/java/com/cognifide/aemrules/htl/HtlSensor.java +++ b/src/main/java/com/vml/aemrules/htl/HtlSensor.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,21 +17,12 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; -import com.cognifide.aemrules.htl.api.HtlCheck; -import com.cognifide.aemrules.htl.lex.HtlLexer; -import com.cognifide.aemrules.htl.visitors.DefaultHtlVisitor; -import com.cognifide.aemrules.htl.visitors.HtlScanner; -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; +import com.vml.aemrules.htl.api.HtlCheck; +import com.vml.aemrules.htl.lex.HtlLexer; +import com.vml.aemrules.htl.visitors.DefaultHtlVisitor; +import com.vml.aemrules.htl.visitors.HtlScanner; import org.sonar.api.batch.Phase; import org.sonar.api.batch.fs.FilePredicate; import org.sonar.api.batch.fs.InputFile; @@ -45,7 +36,16 @@ import org.sonar.api.rule.RuleKey; import org.sonar.plugins.html.node.Node; import org.sonar.plugins.html.visitor.HtmlSourceCode; -import org.sonar.squidbridge.ProgressReport; +import org.sonarsource.analyzer.commons.ProgressReport; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; @Phase(name = Phase.Name.PRE) public class HtlSensor extends HtlFilesAnalyzer implements Sensor { @@ -54,7 +54,7 @@ public class HtlSensor extends HtlFilesAnalyzer implements Sensor { private final FileLinesContextFactory fileLinesContextFactory; - private Configuration configuration; + private final Configuration configuration; public HtlSensor(FileLinesContextFactory fileLinesContextFactory, Configuration configuration, CheckFactory checkFactory) { super(checkFactory); @@ -65,8 +65,8 @@ public HtlSensor(FileLinesContextFactory fileLinesContextFactory, Configuration @Override public void describe(SensorDescriptor descriptor) { descriptor - .name(Htl.NAME) - .onlyOnFileType(Type.MAIN); + .name(Htl.LANGUAGE_NAME) + .onlyOnFileType(Type.MAIN); } @Override @@ -74,13 +74,12 @@ public void execute(SensorContext context) { FilePredicate htlFilePredicate = HtlFilePredicateProvider.createFilePredicate(configuration, context); Iterable inputFiles = context.fileSystem().inputFiles(htlFilePredicate); - Collection files = StreamSupport.stream(inputFiles.spliterator(), false) - .map(InputFile::uri) - .map(File::new) - .collect(Collectors.toList()); + Collection files = StreamSupport.stream(inputFiles.spliterator(), false) + .map(InputFile::filename) + .collect(Collectors.toList()); ProgressReport progressReport = new ProgressReport("Report about progress of HTL analyzer", - TimeUnit.SECONDS.toMillis(10)); + TimeUnit.SECONDS.toMillis(10)); progressReport.start(files); analyseFiles(context, inputFiles, progressReport); } diff --git a/src/main/java/com/cognifide/aemrules/htl/MetricsSaver.java b/src/main/java/com/vml/aemrules/htl/MetricsSaver.java similarity index 86% rename from src/main/java/com/cognifide/aemrules/htl/MetricsSaver.java rename to src/main/java/com/vml/aemrules/htl/MetricsSaver.java index e8a29aff..275e5c6c 100644 --- a/src/main/java/com/cognifide/aemrules/htl/MetricsSaver.java +++ b/src/main/java/com/vml/aemrules/htl/MetricsSaver.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,9 +17,8 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; -import java.util.Map; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.issue.NewIssue; @@ -31,6 +30,8 @@ import org.sonar.plugins.html.checks.HtmlIssue; import org.sonar.plugins.html.visitor.HtmlSourceCode; +import java.util.Map; + public final class MetricsSaver { private MetricsSaver() { @@ -42,12 +43,12 @@ public static void saveIssues(SensorContext context, HtmlSourceCode sourceCode) for (HtmlIssue issue : sourceCode.getIssues()) { NewIssue newIssue = context.newIssue() - .forRule(issue.ruleKey()) - .gap(issue.cost()); + .forRule(issue.ruleKey()) + .gap(issue.cost()); Integer line = issue.line(); NewIssueLocation location = newIssue.newLocation() - .on(inputFile) - .message(issue.message()); + .on(inputFile) + .message(issue.message()); if (line != null && line > 0) { location.at(inputFile.selectLine(line)); } @@ -60,10 +61,10 @@ public static void saveMeasures(SensorContext context, HtmlSourceCode sourceCode InputFile inputFile = sourceCode.inputFile(); for (Map.Entry, Integer> entry : sourceCode.getMeasures().entrySet()) { context.newMeasure() - .on(inputFile) - .forMetric(entry.getKey()) - .withValue(entry.getValue()) - .save(); + .on(inputFile) + .forMetric(entry.getKey()) + .withValue(entry.getValue()) + .save(); } } diff --git a/src/main/java/com/cognifide/aemrules/htl/api/HtlCheck.java b/src/main/java/com/vml/aemrules/htl/api/HtlCheck.java similarity index 89% rename from src/main/java/com/cognifide/aemrules/htl/api/HtlCheck.java rename to src/main/java/com/vml/aemrules/htl/api/HtlCheck.java index 86990dba..b5c5d0e2 100644 --- a/src/main/java/com/cognifide/aemrules/htl/api/HtlCheck.java +++ b/src/main/java/com/vml/aemrules/htl/api/HtlCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.api; +package com.vml.aemrules.htl.api; import org.sonar.api.rule.RuleKey; diff --git a/src/main/java/com/cognifide/aemrules/htl/api/ParsingErrorRule.java b/src/main/java/com/vml/aemrules/htl/api/ParsingErrorRule.java similarity index 88% rename from src/main/java/com/cognifide/aemrules/htl/api/ParsingErrorRule.java rename to src/main/java/com/vml/aemrules/htl/api/ParsingErrorRule.java index 28ee4214..c18cee83 100644 --- a/src/main/java/com/cognifide/aemrules/htl/api/ParsingErrorRule.java +++ b/src/main/java/com/vml/aemrules/htl/api/ParsingErrorRule.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.api; +package com.vml.aemrules.htl.api; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/AbstractHtlCheck.java b/src/main/java/com/vml/aemrules/htl/checks/AbstractHtlCheck.java similarity index 82% rename from src/main/java/com/cognifide/aemrules/htl/checks/AbstractHtlCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/AbstractHtlCheck.java index a66adcf6..f40719d2 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/AbstractHtlCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/AbstractHtlCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,13 +17,10 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.htl.api.HtlCheck; -import com.cognifide.aemrules.htl.visitors.DefaultHtlVisitor; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; +import com.vml.aemrules.htl.api.HtlCheck; +import com.vml.aemrules.htl.visitors.DefaultHtlVisitor; import org.apache.sling.scripting.sightly.compiler.expression.Expression; import org.apache.sling.scripting.sightly.impl.compiler.frontend.ExpressionParser; import org.apache.sling.scripting.sightly.impl.compiler.frontend.Fragment; @@ -31,20 +28,22 @@ import org.sonar.plugins.html.checks.HtmlIssue; import org.sonar.plugins.html.visitor.HtmlSourceCode; -public class AbstractHtlCheck implements DefaultHtlVisitor, HtlCheck { +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; - private HtmlSourceCode htmlSourceCode; +public class AbstractHtlCheck implements DefaultHtlVisitor, HtlCheck { private static final ExpressionParser EXPRESSION_PARSER = new ExpressionParser(); - + private HtmlSourceCode htmlSourceCode; private RuleKey ruleKey; protected static List getExpressions(String code) { Iterable fragments = EXPRESSION_PARSER.parseInterpolation(code).getFragments(); return StreamSupport.stream(fragments.spliterator(), false) - .filter(Fragment::isExpression) - .map(Fragment::getExpression) - .collect(Collectors.toList()); + .filter(Fragment::isExpression) + .map(Fragment::getExpression) + .collect(Collectors.toList()); } @Override @@ -55,14 +54,14 @@ public final void setRuleKey(RuleKey ruleKey) { @Override public final void createViolation(Integer line, String message) { getHtmlSourceCode().addIssue( - new HtmlIssue(ruleKey, line, message) + new HtmlIssue(ruleKey, line, message) ); } @Override public final void createViolation(Integer line, String message, Double cost) { getHtmlSourceCode().addIssue( - new HtmlIssue(ruleKey, line, message, cost) + new HtmlIssue(ruleKey, line, message, cost) ); } @@ -76,5 +75,4 @@ public void setSourceCode(HtmlSourceCode sourceCode) { this.htmlSourceCode = sourceCode; } - } diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/AvoidExtraSlyTagsCheck.java b/src/main/java/com/vml/aemrules/htl/checks/AvoidExtraSlyTagsCheck.java similarity index 79% rename from src/main/java/com/cognifide/aemrules/htl/checks/AvoidExtraSlyTagsCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/AvoidExtraSlyTagsCheck.java index bc79608d..0102d739 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/AvoidExtraSlyTagsCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/AvoidExtraSlyTagsCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,13 +17,10 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; +import com.vml.aemrules.version.AemVersion; import org.apache.commons.lang3.StringUtils; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.html.node.Attribute; import org.sonar.plugins.html.node.TagNode; @@ -32,18 +29,8 @@ import java.util.List; import java.util.Optional; -@Rule( - key = AvoidExtraSlyTagsCheck.RULE_KEY, - name = AvoidExtraSlyTagsCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "5min" -) +@Rule(key = AvoidExtraSlyTagsCheck.RULE_KEY) +@AemVersion(from = "6.0") public class AvoidExtraSlyTagsCheck extends AbstractHtlCheck { public static final String RULE_KEY = "HTL-11"; @@ -61,9 +48,9 @@ public void startElement(TagNode node) { Optional.ofNullable(node.getParent()) .ifPresent(parentNode -> { - if (!StringUtils.equalsAnyIgnoreCase(SLY_TAG,node.getNodeName()) && + if (!StringUtils.equalsAnyIgnoreCase(SLY_TAG, node.getNodeName()) && StringUtils.equalsAnyIgnoreCase(SLY_TAG, parentNode.getNodeName()) && - parentNode.getChildren().size() <= 1){ + parentNode.getChildren().size() <= 1) { parentNode.getAttributes().stream() .map(Attribute::getName) .filter(SLY_ATTRIBUTES::contains) @@ -73,4 +60,3 @@ public void startElement(TagNode node) { }); } } - diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/AvoidUsingUnsafeDisplayContextCheck.java b/src/main/java/com/vml/aemrules/htl/checks/AvoidUsingUnsafeDisplayContextCheck.java similarity index 73% rename from src/main/java/com/cognifide/aemrules/htl/checks/AvoidUsingUnsafeDisplayContextCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/AvoidUsingUnsafeDisplayContextCheck.java index 2cdb0384..4f77c33f 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/AvoidUsingUnsafeDisplayContextCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/AvoidUsingUnsafeDisplayContextCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,32 +17,19 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.htl.visitors.HtlStringOptionVisitor; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; +import com.vml.aemrules.htl.visitors.HtlStringOptionVisitor; +import com.vml.aemrules.version.AemVersion; import org.apache.commons.lang3.StringUtils; import org.apache.sling.scripting.sightly.compiler.expression.Expression; import org.apache.sling.scripting.sightly.compiler.expression.MarkupContext; import org.apache.sling.scripting.sightly.impl.compiler.Syntax; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.html.node.Node; -@Rule( - key = AvoidUsingUnsafeDisplayContextCheck.RULE_KEY, - name = AvoidUsingUnsafeDisplayContextCheck.RULE_MESSAGE, - priority = Priority.CRITICAL, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "5min" -) +@Rule(key = AvoidUsingUnsafeDisplayContextCheck.RULE_KEY) +@AemVersion(from = "6.0") public class AvoidUsingUnsafeDisplayContextCheck extends AbstractHtlCheck { public static final String RULE_KEY = "HTL-13"; @@ -57,6 +44,5 @@ public void htlExpression(Expression expression, Node node) { createViolation(node.getStartLinePosition(), RULE_MESSAGE); } } - } } diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/CamelCaseCheck.java b/src/main/java/com/vml/aemrules/htl/checks/CamelCaseCheck.java similarity index 78% rename from src/main/java/com/cognifide/aemrules/htl/checks/CamelCaseCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/CamelCaseCheck.java index 86dc60c2..a054dc09 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/CamelCaseCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/CamelCaseCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,34 +17,22 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import java.util.List; -import java.util.regex.Pattern; -import javax.annotation.Nonnull; -import org.apache.commons.lang.StringUtils; +import com.vml.aemrules.version.AemVersion; +import org.apache.commons.lang3.StringUtils; import org.apache.sling.scripting.sightly.compiler.expression.Expression; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.html.node.Attribute; import org.sonar.plugins.html.node.TagNode; -@Rule( - key = CamelCaseCheck.RULE_KEY, - name = CamelCaseCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "5min" -) +import javax.annotation.Nonnull; +import java.util.List; +import java.util.regex.Pattern; + +@Rule(key = CamelCaseCheck.RULE_KEY) +@AemVersion(from = "6.0") public class CamelCaseCheck extends AbstractHtlCheck { public static final String RULE_KEY = "HTL-15"; diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/DefaultDisplayContextCheck.java b/src/main/java/com/vml/aemrules/htl/checks/DefaultDisplayContextCheck.java similarity index 52% rename from src/main/java/com/cognifide/aemrules/htl/checks/DefaultDisplayContextCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/DefaultDisplayContextCheck.java index 2107bcde..a581338e 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/DefaultDisplayContextCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/DefaultDisplayContextCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,9 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import org.sonar.check.Priority; +import com.vml.aemrules.version.AemVersion; import org.sonar.check.Rule; import org.sonar.plugins.html.node.TagNode; @@ -35,18 +32,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -@Rule( - key = DefaultDisplayContextCheck.RULE_KEY, - name = DefaultDisplayContextCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "5min" -) +@Rule(key = DefaultDisplayContextCheck.RULE_KEY) +@AemVersion(from = "6.0") public class DefaultDisplayContextCheck extends AbstractHtlCheck { public static final String RULE_KEY = "HTL-6"; @@ -58,27 +45,27 @@ public class DefaultDisplayContextCheck extends AbstractHtlCheck { private static final String VIOLATION_MESSAGE = "Explicitly using default display context, please remove display context from expression"; private static final Map> TAG_ATTRIBUTE_MAPPING = Stream.of( - new AbstractMap.SimpleImmutableEntry<>("a", Arrays.asList("href")), - new AbstractMap.SimpleImmutableEntry<>("area", Arrays.asList("href")), - new AbstractMap.SimpleImmutableEntry<>("audio", Arrays.asList("src")), - new AbstractMap.SimpleImmutableEntry<>("base", Arrays.asList("href")), - new AbstractMap.SimpleImmutableEntry<>("blockquote", Arrays.asList("cite")), - new AbstractMap.SimpleImmutableEntry<>("button", Arrays.asList("formaction")), - new AbstractMap.SimpleImmutableEntry<>("del", Arrays.asList("cite")), - new AbstractMap.SimpleImmutableEntry<>("embed", Arrays.asList("src")), - new AbstractMap.SimpleImmutableEntry<>("form", Arrays.asList("action")), - new AbstractMap.SimpleImmutableEntry<>("html", Arrays.asList("manifest")), - new AbstractMap.SimpleImmutableEntry<>("img", Arrays.asList("src")), - new AbstractMap.SimpleImmutableEntry<>("ins", Arrays.asList("cite")), + new AbstractMap.SimpleImmutableEntry<>("a", List.of("href")), + new AbstractMap.SimpleImmutableEntry<>("area", List.of("href")), + new AbstractMap.SimpleImmutableEntry<>("audio", List.of("src")), + new AbstractMap.SimpleImmutableEntry<>("base", List.of("href")), + new AbstractMap.SimpleImmutableEntry<>("blockquote", List.of("cite")), + new AbstractMap.SimpleImmutableEntry<>("button", List.of("formaction")), + new AbstractMap.SimpleImmutableEntry<>("del", List.of("cite")), + new AbstractMap.SimpleImmutableEntry<>("embed", List.of("src")), + new AbstractMap.SimpleImmutableEntry<>("form", List.of("action")), + new AbstractMap.SimpleImmutableEntry<>("html", List.of("manifest")), + new AbstractMap.SimpleImmutableEntry<>("img", List.of("src")), + new AbstractMap.SimpleImmutableEntry<>("ins", List.of("cite")), new AbstractMap.SimpleImmutableEntry<>("input", Arrays.asList("formaction", "src")), - new AbstractMap.SimpleImmutableEntry<>("iframe", Arrays.asList("src")), - new AbstractMap.SimpleImmutableEntry<>("link", Arrays.asList("href")), - new AbstractMap.SimpleImmutableEntry<>("q", Arrays.asList("cite")), - new AbstractMap.SimpleImmutableEntry<>("object", Arrays.asList("data")), - new AbstractMap.SimpleImmutableEntry<>("video", Arrays.asList("poster")), - new AbstractMap.SimpleImmutableEntry<>("script", Arrays.asList("src")), - new AbstractMap.SimpleImmutableEntry<>("source", Arrays.asList("src")), - new AbstractMap.SimpleImmutableEntry<>("track", Arrays.asList("src")) + new AbstractMap.SimpleImmutableEntry<>("iframe", List.of("src")), + new AbstractMap.SimpleImmutableEntry<>("link", List.of("href")), + new AbstractMap.SimpleImmutableEntry<>("q", List.of("cite")), + new AbstractMap.SimpleImmutableEntry<>("object", List.of("data")), + new AbstractMap.SimpleImmutableEntry<>("video", List.of("poster")), + new AbstractMap.SimpleImmutableEntry<>("script", List.of("src")), + new AbstractMap.SimpleImmutableEntry<>("source", List.of("src")), + new AbstractMap.SimpleImmutableEntry<>("track", List.of("src")) ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); @Override diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/DisplayContextInConditionalCommentsCheck.java b/src/main/java/com/vml/aemrules/htl/checks/DisplayContextInConditionalCommentsCheck.java similarity index 74% rename from src/main/java/com/cognifide/aemrules/htl/checks/DisplayContextInConditionalCommentsCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/DisplayContextInConditionalCommentsCheck.java index 2db98a5f..cadae710 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/DisplayContextInConditionalCommentsCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/DisplayContextInConditionalCommentsCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,30 +17,18 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import java.util.regex.Pattern; +import com.vml.aemrules.version.AemVersion; import org.apache.commons.lang3.StringUtils; import org.apache.sling.scripting.sightly.impl.compiler.Syntax; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.html.node.CommentNode; -@Rule( - key = DisplayContextInConditionalCommentsCheck.RULE_KEY, - name = DisplayContextInConditionalCommentsCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "5min" -) +import java.util.regex.Pattern; + +@Rule(key = DisplayContextInConditionalCommentsCheck.RULE_KEY) +@AemVersion(from = "6.0") public class DisplayContextInConditionalCommentsCheck extends AbstractHtlCheck { public static final String RULE_KEY = "HTL-14"; @@ -52,7 +40,7 @@ public class DisplayContextInConditionalCommentsCheck extends AbstractHtlCheck { @Override public void comment(CommentNode node) { String code = StringUtils.deleteWhitespace(node.getCode()); - if(isConditionalComment(code)){ + if (isConditionalComment(code)) { getExpressions(code).stream() .filter(expression -> !expression.containsOption(Syntax.CONTEXT_OPTION)) .forEach(expression -> createViolation(node.getStartLinePosition(), RULE_MESSAGE)); diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/EventMandatoryDisplayContextCheck.java b/src/main/java/com/vml/aemrules/htl/checks/EventMandatoryDisplayContextCheck.java similarity index 77% rename from src/main/java/com/cognifide/aemrules/htl/checks/EventMandatoryDisplayContextCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/EventMandatoryDisplayContextCheck.java index c2dfb539..70925771 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/EventMandatoryDisplayContextCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/EventMandatoryDisplayContextCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,31 +17,18 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; +import com.vml.aemrules.version.AemVersion; import org.apache.commons.lang3.StringUtils; import org.apache.sling.scripting.sightly.impl.compiler.Syntax; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.html.node.Attribute; import org.sonar.plugins.html.node.TagNode; -@Rule( - key = EventMandatoryDisplayContextCheck.RULE_KEY, - name = EventMandatoryDisplayContextCheck.RULE_MESSAGE, - priority = Priority.MAJOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "5min" -) +@Rule(key = EventMandatoryDisplayContextCheck.RULE_KEY) +@AemVersion(from = "6.0") public class EventMandatoryDisplayContextCheck extends AbstractHtlCheck { public static final String RULE_KEY = "HTL-8"; diff --git a/src/main/java/com/vml/aemrules/htl/checks/ExplicitNamesInLoopsCheck.java b/src/main/java/com/vml/aemrules/htl/checks/ExplicitNamesInLoopsCheck.java new file mode 100644 index 00000000..b818d0a7 --- /dev/null +++ b/src/main/java/com/vml/aemrules/htl/checks/ExplicitNamesInLoopsCheck.java @@ -0,0 +1,50 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.checks; + +import com.vml.aemrules.version.AemVersion; +import org.sonar.check.Rule; +import org.sonar.plugins.html.node.TagNode; + +@Rule(key = ExplicitNamesInLoopsCheck.RULE_KEY) +@AemVersion(all = true) +public class ExplicitNamesInLoopsCheck extends AbstractHtlCheck { + + static final String RULE_KEY = "HTL-3"; + + static final String RULE_MESSAGE = "Use explicit names in loops"; + + @Override + public void startElement(TagNode node) { + if (isSlyList(node) || isSlyRepeat(node)) { + createViolation(node.getStartLinePosition(), RULE_MESSAGE); + } + } + + private boolean isSlyList(TagNode node) { + return node.getAttributes().stream() + .anyMatch(attribute -> "data-sly-list".equals(attribute.getName())); + } + + private boolean isSlyRepeat(TagNode node) { + return node.getAttributes().stream() + .anyMatch(attribute -> "data-sly-repeat".equals(attribute.getName())); + } +} diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/HtlAttributesShouldBeAtTheEndCheck.java b/src/main/java/com/vml/aemrules/htl/checks/HtlAttributesShouldBeAtTheEndCheck.java similarity index 63% rename from src/main/java/com/cognifide/aemrules/htl/checks/HtlAttributesShouldBeAtTheEndCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/HtlAttributesShouldBeAtTheEndCheck.java index 9f4dcbe1..2410809b 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/HtlAttributesShouldBeAtTheEndCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/HtlAttributesShouldBeAtTheEndCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,41 +17,26 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.utils.Comparables; -import com.cognifide.aemrules.version.AemVersion; -import java.util.List; -import java.util.stream.Collectors; +package com.vml.aemrules.htl.checks; +import com.vml.aemrules.utils.Comparables; +import com.vml.aemrules.version.AemVersion; import org.apache.commons.lang3.BooleanUtils; import org.apache.sling.scripting.sightly.compiler.expression.Expression; import org.apache.sling.scripting.sightly.impl.compiler.Syntax; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.html.node.Attribute; import org.sonar.plugins.html.node.TagNode; -@Rule( - key = HtlAttributesShouldBeAtTheEndCheck.RULE_KEY, - name = HtlAttributesShouldBeAtTheEndCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "5min" -) +import java.util.List; +import java.util.stream.Collectors; + +@Rule(key = HtlAttributesShouldBeAtTheEndCheck.RULE_KEY) +@AemVersion(from = "6.0") public class HtlAttributesShouldBeAtTheEndCheck extends AbstractHtlCheck { public static final String RULE_KEY = "HTL-1"; - static final String RULE_MESSAGE = "Always place HTL attributes at the end"; - private static boolean isOrdered(Iterable list) { return Comparables.isOrdered(list); } @@ -59,11 +44,11 @@ private static boolean isOrdered(Iterable list) { @Override public void startHtlElement(List expressions, TagNode node) { Boolean hasAttributesInWrongOrder = node.getAttributes().stream() - .map(Attribute::getName) - .map(Syntax::isPluginAttribute) - .mapToInt(value -> BooleanUtils.isTrue(value) ? 1 : 0) - .boxed() - .collect(Collectors.collectingAndThen(Collectors.toList(), listOfAttributes -> !isOrdered(listOfAttributes))); + .map(Attribute::getName) + .map(Syntax::isPluginAttribute) + .mapToInt(value -> BooleanUtils.isTrue(value) ? 1 : 0) + .boxed() + .collect(Collectors.collectingAndThen(Collectors.toList(), listOfAttributes -> !isOrdered(listOfAttributes))); if (Boolean.TRUE.equals(hasAttributesInWrongOrder)) { createViolation(node.getStartLinePosition(), "Move HTL Attributes to the end of the tag"); } diff --git a/src/main/java/com/vml/aemrules/htl/checks/HtlCommentsCheck.java b/src/main/java/com/vml/aemrules/htl/checks/HtlCommentsCheck.java new file mode 100644 index 00000000..85412b1b --- /dev/null +++ b/src/main/java/com/vml/aemrules/htl/checks/HtlCommentsCheck.java @@ -0,0 +1,83 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.checks; + +import com.vml.aemrules.version.AemVersion; +import org.apache.commons.lang3.StringUtils; +import org.apache.sling.scripting.sightly.impl.compiler.Syntax; +import org.sonar.check.Rule; +import org.sonar.plugins.html.node.CommentNode; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +@Rule(key = HtlCommentsCheck.RULE_KEY) +@AemVersion(all = true) +public class HtlCommentsCheck extends AbstractHtlCheck { + + static final String RULE_KEY = "HTL-5"; + + static final String RULE_MESSAGE = "Always use HTL style of comments"; + + private static final List SSI_ELEMENTS = Arrays.asList("comment", "config", "echo", "exec", "fsize", "flastmod", + "include", "printenv", "set"); + + private static final Pattern CONDITIONAL_COMMENT_PATTERN = Pattern + .compile(""); + + private static final Pattern ESI_COMMENT_PATTERN = Pattern + .compile(""); + + private static final List EXCEPTIONS = buildExceptionList(); + + private static List buildExceptionList() { + List result = new ArrayList<>(); + result.add(CONDITIONAL_COMMENT_PATTERN); + result.add(ESI_COMMENT_PATTERN); + result.addAll(buildSsiRegex(SSI_ELEMENTS)); + + return result; + } + + private static List buildSsiRegex(List elements) { + return elements.stream() + .map(e -> "") + .map(Pattern::compile) + .collect(Collectors.toList()); + } + + @Override + public void comment(CommentNode node) { + String code = StringUtils.deleteWhitespace(node.getCode()); + if (!Syntax.isSightlyComment(code) && !isException(code)) { + createViolation(node.getStartLinePosition(), RULE_MESSAGE); + } + } + + private boolean isException(String code) { + return EXCEPTIONS.stream() + .map(pattern -> pattern.matcher(code)) + .anyMatch(Matcher::matches); + } +} \ No newline at end of file diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/InlineStyleMandatoryDisplayContextCheck.java b/src/main/java/com/vml/aemrules/htl/checks/InlineStyleMandatoryDisplayContextCheck.java similarity index 76% rename from src/main/java/com/cognifide/aemrules/htl/checks/InlineStyleMandatoryDisplayContextCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/InlineStyleMandatoryDisplayContextCheck.java index 38216215..eac13f19 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/InlineStyleMandatoryDisplayContextCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/InlineStyleMandatoryDisplayContextCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,31 +17,18 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; +import com.vml.aemrules.version.AemVersion; import org.apache.commons.lang3.StringUtils; import org.apache.sling.scripting.sightly.impl.compiler.Syntax; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.html.node.Attribute; import org.sonar.plugins.html.node.TagNode; -@Rule( - key = InlineStyleMandatoryDisplayContextCheck.RULE_KEY, - name = InlineStyleMandatoryDisplayContextCheck.RULE_MESSAGE, - priority = Priority.MAJOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "5min" -) +@Rule(key = InlineStyleMandatoryDisplayContextCheck.RULE_KEY) +@AemVersion(from = "6.0") public class InlineStyleMandatoryDisplayContextCheck extends AbstractHtlCheck { public static final String RULE_KEY = "HTL-9"; diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/NamingAndReusingConditionsCheck.java b/src/main/java/com/vml/aemrules/htl/checks/NamingAndReusingConditionsCheck.java similarity index 68% rename from src/main/java/com/cognifide/aemrules/htl/checks/NamingAndReusingConditionsCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/NamingAndReusingConditionsCheck.java index 38c8e2ec..d03887bb 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/NamingAndReusingConditionsCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/NamingAndReusingConditionsCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,34 +17,22 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.htl.api.ParsingErrorRule; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; +import com.vml.aemrules.htl.api.ParsingErrorRule; +import com.vml.aemrules.version.AemVersion; import org.apache.sling.scripting.sightly.compiler.expression.Expression; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.html.node.Attribute; import org.sonar.plugins.html.node.TagNode; -@Rule( - key = NamingAndReusingConditionsCheck.RULE_KEY, - name = NamingAndReusingConditionsCheck.RULE_MESSAGE, - priority = Priority.INFO, - tags = Tags.AEM -) -@AemVersion( - all = true -) -@Metadata( - technicalDebt = "10min" -) +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +@Rule(key = NamingAndReusingConditionsCheck.RULE_KEY) +@AemVersion(all = true) @ParsingErrorRule public class NamingAndReusingConditionsCheck extends AbstractHtlCheck { @@ -56,9 +44,9 @@ public class NamingAndReusingConditionsCheck extends AbstractHtlCheck { private static final int SLY_TEST_LENGTH = 14; - private Set unnamedConditions = new HashSet<>(); + private final Set unnamedConditions = new HashSet<>(); - private Set namedConditions = new HashSet<>(); + private final Set namedConditions = new HashSet<>(); @Override public void startHtlElement(List expressions, TagNode node) { @@ -76,43 +64,43 @@ public void endDocument() { private boolean isConditionReusedCorrectly(List expressions, TagNode node) { String condition = clearExpressions(expressions).stream() - .findFirst() - .orElse(""); + .findFirst() + .orElse(""); return !(isUnnamedConditionReused(condition) && isNewUnnamedConditionDeclared(node)); } private boolean isNewUnnamedConditionDeclared(TagNode node) { return node.getAttributes().stream() - .map(Attribute::getName) - .anyMatch(SLY_TEST::equals); + .map(Attribute::getName) + .anyMatch(SLY_TEST::equals); } private boolean isUnnamedConditionReused(String condition) { return unnamedConditions.stream() - .anyMatch(condition::equals); + .anyMatch(condition::equals); } private void updateConditionSets(List expressions, TagNode node) { String condition = node.getAttributes().stream() - .map(Attribute::getName) - .filter(text -> text.contains(SLY_TEST)) - .findFirst() - .orElse(""); + .map(Attribute::getName) + .filter(text -> text.contains(SLY_TEST)) + .findFirst() + .orElse(""); if (!SLY_TEST.equals(condition) && SLY_TEST_LENGTH < condition.length()) { condition = condition.substring(SLY_TEST_LENGTH); namedConditions.add(condition); } else { unnamedConditions.addAll(clearExpressions(expressions).stream() - .filter(text -> !namedConditions.contains(text)) - .collect(Collectors.toSet())); + .filter(text -> !namedConditions.contains(text)) + .collect(Collectors.toSet())); } } - private Set clearExpressions(List expressions){ + private Set clearExpressions(List expressions) { return expressions.stream() - .map(Expression::getRawText) - .map(text -> text.replaceAll("[${}]", "")) - .collect(Collectors.toSet()); + .map(Expression::getRawText) + .map(text -> text.replaceAll("[${}]", "")) + .collect(Collectors.toSet()); } } \ No newline at end of file diff --git a/src/main/java/com/vml/aemrules/htl/checks/ParsingErrorCheck.java b/src/main/java/com/vml/aemrules/htl/checks/ParsingErrorCheck.java new file mode 100644 index 00000000..9022df9d --- /dev/null +++ b/src/main/java/com/vml/aemrules/htl/checks/ParsingErrorCheck.java @@ -0,0 +1,31 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.checks; + +import com.vml.aemrules.htl.api.ParsingErrorRule; +import com.vml.aemrules.version.AemVersion; +import org.sonar.check.Rule; + +@Rule(key = ParsingErrorCheck.RULE_KEY) +@AemVersion(from = "6.0") +@ParsingErrorRule +public class ParsingErrorCheck extends AbstractHtlCheck { + static final String RULE_KEY = "HTL-0"; +} diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/PlaceTemplatesInSeparateFilesCheck.java b/src/main/java/com/vml/aemrules/htl/checks/PlaceTemplatesInSeparateFilesCheck.java similarity index 86% rename from src/main/java/com/cognifide/aemrules/htl/checks/PlaceTemplatesInSeparateFilesCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/PlaceTemplatesInSeparateFilesCheck.java index 02c0d906..807e9fa8 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/PlaceTemplatesInSeparateFilesCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/PlaceTemplatesInSeparateFilesCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,14 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import org.apache.commons.lang.StringUtils; +import com.vml.aemrules.version.AemVersion; +import org.apache.commons.lang3.StringUtils; import org.apache.sling.scripting.sightly.compiler.expression.Expression; import org.apache.sling.scripting.sightly.compiler.expression.ExpressionNode; import org.apache.sling.scripting.sightly.compiler.expression.nodes.Identifier; import org.apache.sling.scripting.sightly.compiler.expression.nodes.PropertyAccess; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.html.node.Attribute; import org.sonar.plugins.html.node.TagNode; @@ -37,27 +34,17 @@ import java.util.Map; import java.util.Objects; -@Rule( - key = PlaceTemplatesInSeparateFilesCheck.RULE_KEY, - name = PlaceTemplatesInSeparateFilesCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "15min" -) +@Rule(key = PlaceTemplatesInSeparateFilesCheck.RULE_KEY) +@AemVersion(from = "6.0") public class PlaceTemplatesInSeparateFilesCheck extends AbstractHtlCheck { public static final String RULE_KEY = "HTL-2"; public static final String RULE_MESSAGE = "HTL Templates should be placed in separate files"; - private Map templatesDefinition; + private final Map templatesDefinition; - private Map templatesCalls; + private final Map templatesCalls; public PlaceTemplatesInSeparateFilesCheck() { templatesDefinition = new HashMap<>(); diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/ScriptsAndStyleMandatoryDisplayContextCheck.java b/src/main/java/com/vml/aemrules/htl/checks/ScriptsAndStyleMandatoryDisplayContextCheck.java similarity index 78% rename from src/main/java/com/cognifide/aemrules/htl/checks/ScriptsAndStyleMandatoryDisplayContextCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/ScriptsAndStyleMandatoryDisplayContextCheck.java index 5b234569..83bdb9c7 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/ScriptsAndStyleMandatoryDisplayContextCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/ScriptsAndStyleMandatoryDisplayContextCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,31 +17,18 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; +import com.vml.aemrules.version.AemVersion; import org.apache.sling.scripting.sightly.compiler.expression.Expression; import org.apache.sling.scripting.sightly.impl.compiler.Syntax; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.html.node.Node; import org.sonar.plugins.html.node.TagNode; -@Rule( - key = ScriptsAndStyleMandatoryDisplayContextCheck.RULE_KEY, - name = ScriptsAndStyleMandatoryDisplayContextCheck.RULE_MESSAGE, - priority = Priority.MAJOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "5min" -) +@Rule(key = ScriptsAndStyleMandatoryDisplayContextCheck.RULE_KEY) +@AemVersion(from = "6.0") public class ScriptsAndStyleMandatoryDisplayContextCheck extends AbstractHtlCheck { public static final String RULE_KEY = "HTL-7"; diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/SlyElementsAreAutomaticallyUnwrappedCheck.java b/src/main/java/com/vml/aemrules/htl/checks/SlyElementsAreAutomaticallyUnwrappedCheck.java similarity index 78% rename from src/main/java/com/cognifide/aemrules/htl/checks/SlyElementsAreAutomaticallyUnwrappedCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/SlyElementsAreAutomaticallyUnwrappedCheck.java index 22c41ced..cb3dc8ff 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/SlyElementsAreAutomaticallyUnwrappedCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/SlyElementsAreAutomaticallyUnwrappedCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,31 +17,18 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; +import com.vml.aemrules.version.AemVersion; import org.apache.commons.lang3.StringUtils; import org.apache.sling.scripting.sightly.impl.compiler.Syntax; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.html.node.Attribute; import org.sonar.plugins.html.node.TagNode; -@Rule( - key = SlyElementsAreAutomaticallyUnwrappedCheck.RULE_KEY, - name = SlyElementsAreAutomaticallyUnwrappedCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "5min" -) +@Rule(key = SlyElementsAreAutomaticallyUnwrappedCheck.RULE_KEY) +@AemVersion(from = "6.0") public class SlyElementsAreAutomaticallyUnwrappedCheck extends AbstractHtlCheck { public static final String RULE_KEY = "HTL-16"; diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/UseMostRestrictiveHtlContextCheck.java b/src/main/java/com/vml/aemrules/htl/checks/UseMostRestrictiveHtlContextCheck.java similarity index 75% rename from src/main/java/com/cognifide/aemrules/htl/checks/UseMostRestrictiveHtlContextCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/UseMostRestrictiveHtlContextCheck.java index 1d89ce00..e35f0ecb 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/UseMostRestrictiveHtlContextCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/UseMostRestrictiveHtlContextCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,30 +17,17 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; +import com.vml.aemrules.version.AemVersion; import org.apache.commons.lang3.StringUtils; import org.apache.sling.scripting.sightly.impl.compiler.Syntax; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.html.node.Attribute; import org.sonar.plugins.html.node.TagNode; -@Rule( - key = UseMostRestrictiveHtlContextCheck.RULE_KEY, - name = UseMostRestrictiveHtlContextCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "5min" -) +@Rule(key = UseMostRestrictiveHtlContextCheck.RULE_KEY) +@AemVersion(from = "6.0") public class UseMostRestrictiveHtlContextCheck extends AbstractHtlCheck { public static final String RULE_KEY = "HTL-12"; @@ -64,7 +51,7 @@ private boolean isHtmlDataAttribute(Attribute attribute) { } private boolean isNotContextDefined(Attribute attribute) { - return getExpressions(attribute.getValue()).stream() + return getExpressions(attribute.getValue()).stream() .anyMatch(expression -> !expression.containsOption(Syntax.CONTEXT_OPTION)); } } diff --git a/src/main/java/com/cognifide/aemrules/htl/checks/UseSlyTagsOverRedundantMarkupCheck.java b/src/main/java/com/vml/aemrules/htl/checks/UseSlyTagsOverRedundantMarkupCheck.java similarity index 83% rename from src/main/java/com/cognifide/aemrules/htl/checks/UseSlyTagsOverRedundantMarkupCheck.java rename to src/main/java/com/vml/aemrules/htl/checks/UseSlyTagsOverRedundantMarkupCheck.java index 4d02188e..f075ba76 100644 --- a/src/main/java/com/cognifide/aemrules/htl/checks/UseSlyTagsOverRedundantMarkupCheck.java +++ b/src/main/java/com/vml/aemrules/htl/checks/UseSlyTagsOverRedundantMarkupCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,14 +17,11 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; +import com.vml.aemrules.version.AemVersion; import org.apache.commons.lang3.StringUtils; import org.apache.sling.scripting.sightly.compiler.expression.Expression; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.html.node.Attribute; import org.sonar.plugins.html.node.TagNode; @@ -33,18 +30,8 @@ import java.util.List; import java.util.stream.Collectors; -@Rule( - key = UseSlyTagsOverRedundantMarkupCheck.RULE_KEY, - name = UseSlyTagsOverRedundantMarkupCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "5min" -) +@Rule(key = UseSlyTagsOverRedundantMarkupCheck.RULE_KEY) +@AemVersion(from = "6.0") public class UseSlyTagsOverRedundantMarkupCheck extends AbstractHtlCheck { public static final String RULE_KEY = "HTL-10"; @@ -75,13 +62,13 @@ private boolean isWrappedInRedundantMarkup(TagNode node, List expres node.getChildren().isEmpty(); } - private boolean containsRedundantHtmlContainer(TagNode node){ + private boolean containsRedundantHtmlContainer(TagNode node) { return StringUtils.equalsIgnoreCase("div", node.getNodeName()) && node.getAttribute("data-sly-test") != null && node.getAttribute("class") == null; } - private boolean isUsingCallAttributes(TagNode node){ + private boolean isUsingCallAttributes(TagNode node) { return node.getAttributes().stream() .map(Attribute::getName) .map(s -> StringUtils.substringBefore(s, ".")) diff --git a/src/main/java/com/cognifide/aemrules/htl/lex/AbstractTokenizer.java b/src/main/java/com/vml/aemrules/htl/lex/AbstractTokenizer.java similarity index 72% rename from src/main/java/com/cognifide/aemrules/htl/lex/AbstractTokenizer.java rename to src/main/java/com/vml/aemrules/htl/lex/AbstractTokenizer.java index 12d914ed..7328b5b9 100644 --- a/src/main/java/com/cognifide/aemrules/htl/lex/AbstractTokenizer.java +++ b/src/main/java/com/vml/aemrules/htl/lex/AbstractTokenizer.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,20 +17,23 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.lex; +package com.vml.aemrules.htl.lex; -import java.util.List; -import org.sonar.channel.Channel; -import org.sonar.channel.CodeReader; -import org.sonar.channel.EndMatcher; import org.sonar.plugins.html.node.Node; +import org.sonar.sslr.channel.Channel; +import org.sonar.sslr.channel.CodeReader; +import org.sonar.sslr.channel.EndMatcher; + +import java.util.Arrays; +import java.util.List; abstract class AbstractTokenizer> extends Channel { private final char[] endChars; + private final char[] startChars; - public AbstractTokenizer(String startChars, String endChars) { + protected AbstractTokenizer(String startChars, String endChars) { this.startChars = startChars.toCharArray(); this.endChars = endChars.toCharArray(); } @@ -49,6 +52,16 @@ protected static boolean equalsIgnoreCase(char[] a, char[] b) { return true; } + protected static String popTo(CodeReader codeReader, EndMatcher endMatcher, StringBuilder stringBuilder) { + boolean shouldContinue = codeReader.peek() != -1; + while (shouldContinue) { + stringBuilder.append((char) codeReader.pop()); + shouldContinue = !endMatcher.match(codeReader.peek()) && codeReader.peek() != -1; + } + + return stringBuilder.toString(); + } + protected void addNode(List nodeList, Node node) { nodeList.add(node); } @@ -60,7 +73,7 @@ public boolean consume(CodeReader codeReader, T nodeList) { setStartPosition(codeReader, node); StringBuilder stringBuilder = new StringBuilder(); - codeReader.popTo(getEndMatcher(codeReader), stringBuilder); + popTo(codeReader, getEndMatcher(codeReader), stringBuilder); for (int i = 0; i < endChars.length; i++) { codeReader.pop(stringBuilder); } @@ -103,20 +116,22 @@ private EndTokenMatcher(CodeReader codeReader) { @Override public boolean match(int endFlag) { - boolean result = false; if (endFlag == '"') { quoting = !quoting; } if (!quoting) { - if (equalsIgnoreCase(codeReader.peek(startChars.length), startChars)) { + boolean started = equalsIgnoreCase(codeReader.peek(startChars.length), startChars); + if (started) { nesting++; - } else if (equalsIgnoreCase(codeReader.peek(endChars.length), endChars)) { - nesting--; - result = nesting < 0; + } else { + boolean ended = Arrays.equals(codeReader.peek(endChars.length), endChars); + if (ended) { + nesting--; + return nesting < 0; + } } } - - return result; + return false; } } diff --git a/src/main/java/com/cognifide/aemrules/htl/lex/CommentTokenizer.java b/src/main/java/com/vml/aemrules/htl/lex/CommentTokenizer.java similarity index 91% rename from src/main/java/com/cognifide/aemrules/htl/lex/CommentTokenizer.java rename to src/main/java/com/vml/aemrules/htl/lex/CommentTokenizer.java index 3ea5615a..eca3f259 100644 --- a/src/main/java/com/cognifide/aemrules/htl/lex/CommentTokenizer.java +++ b/src/main/java/com/vml/aemrules/htl/lex/CommentTokenizer.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,18 +17,21 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.lex; +package com.vml.aemrules.htl.lex; + -import java.util.List; -import org.sonar.channel.CodeReader; -import org.sonar.channel.EndMatcher; import org.sonar.plugins.html.node.CommentNode; import org.sonar.plugins.html.node.Node; +import org.sonar.sslr.channel.CodeReader; +import org.sonar.sslr.channel.EndMatcher; + +import java.util.List; class CommentTokenizer> extends AbstractTokenizer { private final Boolean isHtml; private final char[] endChars; + public CommentTokenizer(String startToken, String endToken, Boolean isHtml) { super(startToken, endToken); this.isHtml = isHtml; diff --git a/src/main/java/com/cognifide/aemrules/htl/lex/DirectiveTokenizer.java b/src/main/java/com/vml/aemrules/htl/lex/DirectiveTokenizer.java similarity index 90% rename from src/main/java/com/cognifide/aemrules/htl/lex/DirectiveTokenizer.java rename to src/main/java/com/vml/aemrules/htl/lex/DirectiveTokenizer.java index c7ccc5d0..a367711e 100644 --- a/src/main/java/com/cognifide/aemrules/htl/lex/DirectiveTokenizer.java +++ b/src/main/java/com/vml/aemrules/htl/lex/DirectiveTokenizer.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.lex; +package com.vml.aemrules.htl.lex; import org.sonar.plugins.html.node.DirectiveNode; import org.sonar.plugins.html.node.Node; diff --git a/src/main/java/com/cognifide/aemrules/htl/lex/DoctypeTokenizer.java b/src/main/java/com/vml/aemrules/htl/lex/DoctypeTokenizer.java similarity index 92% rename from src/main/java/com/cognifide/aemrules/htl/lex/DoctypeTokenizer.java rename to src/main/java/com/vml/aemrules/htl/lex/DoctypeTokenizer.java index 32c086a9..bdfb543a 100644 --- a/src/main/java/com/cognifide/aemrules/htl/lex/DoctypeTokenizer.java +++ b/src/main/java/com/vml/aemrules/htl/lex/DoctypeTokenizer.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,16 +17,17 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.lex; +package com.vml.aemrules.htl.lex; + +import org.sonar.plugins.html.node.Attribute; +import org.sonar.plugins.html.node.DirectiveNode; +import org.sonar.plugins.html.node.Node; import java.io.IOException; import java.io.Reader; import java.io.StreamTokenizer; import java.io.StringReader; import java.util.List; -import org.sonar.plugins.html.node.Attribute; -import org.sonar.plugins.html.node.DirectiveNode; -import org.sonar.plugins.html.node.Node; class DoctypeTokenizer extends AbstractTokenizer> { @@ -36,7 +37,7 @@ public DoctypeTokenizer(String startToken, String endToken) { private static void parseToken(DirectiveNode node) { String code = node.getCode(); - try(Reader reader = new StringReader(code)) { + try (Reader reader = new StringReader(code)) { StreamTokenizer tokenizer = new StreamTokenizer(reader); tokenizer.quoteChar('"'); while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) { diff --git a/src/main/java/com/cognifide/aemrules/htl/lex/ElementTokenizer.java b/src/main/java/com/vml/aemrules/htl/lex/ElementTokenizer.java similarity index 93% rename from src/main/java/com/cognifide/aemrules/htl/lex/ElementTokenizer.java rename to src/main/java/com/vml/aemrules/htl/lex/ElementTokenizer.java index d1810c42..eb2975f8 100644 --- a/src/main/java/com/cognifide/aemrules/htl/lex/ElementTokenizer.java +++ b/src/main/java/com/vml/aemrules/htl/lex/ElementTokenizer.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,14 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.lex; +package com.vml.aemrules.htl.lex; + +import org.apache.commons.lang3.StringUtils; +import org.sonar.plugins.html.node.Attribute; +import org.sonar.plugins.html.node.Node; +import org.sonar.plugins.html.node.TagNode; +import org.sonar.sslr.channel.CodeReader; +import org.sonar.sslr.channel.EndMatcher; import java.util.ArrayDeque; import java.util.Deque; @@ -26,13 +33,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import org.apache.commons.lang3.StringUtils; -import org.sonar.channel.CodeReader; -import org.sonar.channel.EndMatcher; -import org.sonar.plugins.html.node.Attribute; -import org.sonar.plugins.html.node.Node; -import org.sonar.plugins.html.node.TagNode; - class ElementTokenizer extends AbstractTokenizer> { private static final EndQNameMatcher END_Q_NAME_MATCHER = new EndQNameMatcher(); @@ -77,13 +77,13 @@ private static void handleBeforeAttributeValue(CodeReader codeReader, TagNode el if (isQuote((char) ch)) { codeReader.pop(); if (codeReader.peek() != ch) { - codeReader.popTo(new QuoteMatcher((char) ch), sbValue); + popTo(codeReader, new QuoteMatcher((char) ch), sbValue); attribute.setValue(unescapeQuotes(sbValue.toString(), (char) ch)); } codeReader.pop(); attribute.setQuoteChar((char) ch); } else { - codeReader.popTo(END_UNQUOTED_ATTRIBUTE_MATCHER, sbValue); + popTo(codeReader, END_UNQUOTED_ATTRIBUTE_MATCHER, sbValue); attribute.setValue(sbValue.toString().trim()); } } @@ -92,7 +92,7 @@ private static void handleBeforeAttributeValue(CodeReader codeReader, TagNode el private static void handleBeforeAttributeName(CodeReader codeReader, TagNode element) { Attribute attribute; StringBuilder sbQName = new StringBuilder(); - codeReader.popTo(END_Q_NAME_MATCHER, sbQName); + popTo(codeReader, END_Q_NAME_MATCHER, sbQName); attribute = new Attribute(sbQName.toString().trim()); attribute.setLine(codeReader.getLinePosition() + element.getStartLinePosition() - 1); element.getAttributes().add(attribute); @@ -100,7 +100,7 @@ private static void handleBeforeAttributeName(CodeReader codeReader, TagNode ele private static void handleBeforeNodeName(CodeReader codeReader, TagNode element) { StringBuilder sbNodeName = new StringBuilder(); - codeReader.popTo(END_TOKEN_MATCHER, sbNodeName); + popTo(codeReader, END_TOKEN_MATCHER, sbNodeName); element.setNodeName(sbNodeName.toString()); } @@ -199,12 +199,12 @@ public boolean match(int character) { private static final class EndUnquotedAttributeMatcher implements EndMatcher { private static final Set FORBIDDEN = Stream.of( - '"', - '\'', - '=', - '<', - '>', - '`' + '"', + '\'', + '=', + '<', + '>', + '`' ).collect(Collectors.toSet()); @Override @@ -255,4 +255,4 @@ public boolean match(int character) { } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cognifide/aemrules/htl/lex/ExpressionTokenizer.java b/src/main/java/com/vml/aemrules/htl/lex/ExpressionTokenizer.java similarity index 91% rename from src/main/java/com/cognifide/aemrules/htl/lex/ExpressionTokenizer.java rename to src/main/java/com/vml/aemrules/htl/lex/ExpressionTokenizer.java index 9097f4ed..2b33057f 100644 --- a/src/main/java/com/cognifide/aemrules/htl/lex/ExpressionTokenizer.java +++ b/src/main/java/com/vml/aemrules/htl/lex/ExpressionTokenizer.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,13 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.lex; +package com.vml.aemrules.htl.lex; -import java.util.List; import org.sonar.plugins.html.node.ExpressionNode; import org.sonar.plugins.html.node.Node; +import java.util.List; + class ExpressionTokenizer extends AbstractTokenizer> { public ExpressionTokenizer(String startChars, String endChars) { diff --git a/src/main/java/com/cognifide/aemrules/htl/lex/HtlLexer.java b/src/main/java/com/vml/aemrules/htl/lex/HtlLexer.java similarity index 68% rename from src/main/java/com/cognifide/aemrules/htl/lex/HtlLexer.java rename to src/main/java/com/vml/aemrules/htl/lex/HtlLexer.java index dba78791..87ca0e99 100644 --- a/src/main/java/com/cognifide/aemrules/htl/lex/HtlLexer.java +++ b/src/main/java/com/vml/aemrules/htl/lex/HtlLexer.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,43 +17,45 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.lex; +package com.vml.aemrules.htl.lex; -import java.io.Reader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; import org.apache.sling.scripting.sightly.impl.compiler.Syntax; -import org.sonar.channel.Channel; -import org.sonar.channel.ChannelDispatcher; -import org.sonar.channel.CodeReader; + import org.sonar.plugins.html.node.Node; import org.sonar.plugins.html.node.NodeType; import org.sonar.plugins.html.node.TagNode; +import org.sonar.sslr.channel.Channel; +import org.sonar.sslr.channel.ChannelDispatcher; +import org.sonar.sslr.channel.CodeReader; + +import java.io.Reader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; public final class HtlLexer { - private static List>> tokenizers = Arrays.asList( - /* HTL Comments */ - new CommentTokenizer(Syntax.SLY_COMMENT_PREFIX, Syntax.SLY_COMMENT_SUFFIX, false), - /* HTML Comments */ - new CommentTokenizer("", true), - /* JSP Comments */ - new CommentTokenizer("<%--", "--%>", false), - /* HTML Directive */ - new DoctypeTokenizer(""), - /* XML Directives */ - new DirectiveTokenizer(""), - /* JSP Directives */ - new DirectiveTokenizer("<%@", "%>"), - /* JSP Expressions */ - new ExpressionTokenizer("<%", "%>"), - /* HTL Expressions */ - new ExpressionTokenizer("${", "}"), - /* XML and HTML Tags */ - new ElementTokenizer("<", ">"), - /* Text (for everything else) */ - new TextTokenizer()); + private static final List>> tokenizers = Arrays.asList( + /* HTL Comments */ + new CommentTokenizer<>(Syntax.SLY_COMMENT_PREFIX, Syntax.SLY_COMMENT_SUFFIX, false), + /* HTML Comments */ + new CommentTokenizer<>("", true), + /* JSP Comments */ + new CommentTokenizer<>("<%--", "--%>", false), + /* HTML Directive */ + new DoctypeTokenizer(""), + /* XML Directives */ + new DirectiveTokenizer(""), + /* JSP Directives */ + new DirectiveTokenizer("<%@", "%>"), + /* JSP Expressions */ + new ExpressionTokenizer("<%", "%>"), + /* HTL Expressions */ + new ExpressionTokenizer("${", "}"), + /* XML and HTML Tags */ + new ElementTokenizer("<", ">"), + /* Text (for everything else) */ + new TextTokenizer()); /** * Scan the nodes and build the hierarchy of parent and child nodes. @@ -105,8 +107,8 @@ public List parse(Reader reader) { // ChannelDispatcher manages the tokenizers ChannelDispatcher> channelDispatcher = ChannelDispatcher.builder() - .addChannels(tokenizers.toArray(new Channel[0])) - .build(); + .addChannels(tokenizers.toArray(new Channel[0])) + .build(); channelDispatcher.consume(codeReader, nodeList); createNodeHierarchy(nodeList); diff --git a/src/main/java/com/cognifide/aemrules/htl/lex/TextTokenizer.java b/src/main/java/com/vml/aemrules/htl/lex/TextTokenizer.java similarity index 84% rename from src/main/java/com/cognifide/aemrules/htl/lex/TextTokenizer.java rename to src/main/java/com/vml/aemrules/htl/lex/TextTokenizer.java index b5f761dd..4bccb347 100644 --- a/src/main/java/com/cognifide/aemrules/htl/lex/TextTokenizer.java +++ b/src/main/java/com/vml/aemrules/htl/lex/TextTokenizer.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,15 +17,17 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.lex; +package com.vml.aemrules.htl.lex; + -import java.util.List; -import org.sonar.channel.CodeReader; -import org.sonar.channel.EndMatcher; import org.sonar.plugins.html.node.Node; import org.sonar.plugins.html.node.NodeType; import org.sonar.plugins.html.node.TagNode; import org.sonar.plugins.html.node.TextNode; +import org.sonar.sslr.channel.CodeReader; +import org.sonar.sslr.channel.EndMatcher; + +import java.util.List; class TextTokenizer extends AbstractTokenizer> { @@ -52,9 +54,9 @@ public boolean consume(CodeReader codeReader, List nodeList) { StringBuilder stringBuilder = new StringBuilder(); if (inScript(nodeList)) { - codeReader.popTo(new EndScriptMatcher(codeReader), stringBuilder); + popTo(codeReader, new EndScriptMatcher(codeReader), stringBuilder); } else { - codeReader.popTo(new EndTokenMatcher(codeReader), stringBuilder); + popTo(codeReader, new EndTokenMatcher(codeReader), stringBuilder); } node.setCode(stringBuilder.toString()); setEndPosition(codeReader, node); @@ -79,12 +81,7 @@ private EndTokenMatcher(CodeReader codeReader) { @Override public boolean match(int endFlag) { - boolean match = false; - if ('<' == endFlag || equalsIgnoreCase(codeReader.peek("${".length()), "${".toCharArray())) { - match = true; - } - - return match; + return '<' == endFlag || equalsIgnoreCase(codeReader.peek("${".length()), "${".toCharArray()); } } @@ -113,4 +110,4 @@ public boolean match(int endFlag) { } } -} \ No newline at end of file +} diff --git a/src/main/java/com/vml/aemrules/htl/rules/HtlRulesDefinition.java b/src/main/java/com/vml/aemrules/htl/rules/HtlRulesDefinition.java new file mode 100644 index 00000000..6a2a88d5 --- /dev/null +++ b/src/main/java/com/vml/aemrules/htl/rules/HtlRulesDefinition.java @@ -0,0 +1,49 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.rules; + +import com.vml.aemrules.htl.Htl; +import org.sonar.api.SonarRuntime; +import org.sonar.api.server.rule.RulesDefinition; +import org.sonarsource.analyzer.commons.RuleMetadataLoader; + +import java.util.ArrayList; + +import static com.vml.aemrules.htl.Constants.REPOSITORY_KEY; +import static com.vml.aemrules.htl.Constants.REPOSITORY_NAME; + +public class HtlRulesDefinition implements RulesDefinition { + + public static final String RESOURCE_BASE_PATH = "com/vml/rules/htl"; + + private final SonarRuntime sonarRuntime; + + public HtlRulesDefinition(SonarRuntime sonarRuntime) { + this.sonarRuntime = sonarRuntime; + } + + @Override + public void define(Context context) { + NewRepository repository = context.createRepository(REPOSITORY_KEY, Htl.LANGUAGE_KEY).setName(REPOSITORY_NAME); + RuleMetadataLoader ruleMetadataLoader = new RuleMetadataLoader(RESOURCE_BASE_PATH, sonarRuntime); + ruleMetadataLoader.addRulesByAnnotatedClass(repository, new ArrayList<>(HtlRulesList.getChecks())); + repository.done(); + } +} diff --git a/src/main/java/com/vml/aemrules/htl/rules/HtlRulesList.java b/src/main/java/com/vml/aemrules/htl/rules/HtlRulesList.java new file mode 100644 index 00000000..7470dc73 --- /dev/null +++ b/src/main/java/com/vml/aemrules/htl/rules/HtlRulesList.java @@ -0,0 +1,79 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.rules; + +import com.vml.aemrules.htl.api.HtlCheck; +import com.vml.aemrules.htl.checks.AvoidExtraSlyTagsCheck; +import com.vml.aemrules.htl.checks.AvoidUsingUnsafeDisplayContextCheck; +import com.vml.aemrules.htl.checks.CamelCaseCheck; +import com.vml.aemrules.htl.checks.DefaultDisplayContextCheck; +import com.vml.aemrules.htl.checks.DisplayContextInConditionalCommentsCheck; +import com.vml.aemrules.htl.checks.EventMandatoryDisplayContextCheck; +import com.vml.aemrules.htl.checks.ExplicitNamesInLoopsCheck; +import com.vml.aemrules.htl.checks.HtlAttributesShouldBeAtTheEndCheck; +import com.vml.aemrules.htl.checks.HtlCommentsCheck; +import com.vml.aemrules.htl.checks.InlineStyleMandatoryDisplayContextCheck; +import com.vml.aemrules.htl.checks.NamingAndReusingConditionsCheck; +import com.vml.aemrules.htl.checks.ParsingErrorCheck; +import com.vml.aemrules.htl.checks.PlaceTemplatesInSeparateFilesCheck; +import com.vml.aemrules.htl.checks.ScriptsAndStyleMandatoryDisplayContextCheck; +import com.vml.aemrules.htl.checks.SlyElementsAreAutomaticallyUnwrappedCheck; +import com.vml.aemrules.htl.checks.UseMostRestrictiveHtlContextCheck; +import com.vml.aemrules.htl.checks.UseSlyTagsOverRedundantMarkupCheck; +import org.sonar.check.Rule; + +import java.util.List; +import java.util.Optional; + +public final class HtlRulesList { + + private HtlRulesList() { + //private constructor + } + + public static List> getChecks() { + return List.of( + ParsingErrorCheck.class, + HtlCommentsCheck.class, + AvoidExtraSlyTagsCheck.class, + AvoidUsingUnsafeDisplayContextCheck.class, + DefaultDisplayContextCheck.class, + DisplayContextInConditionalCommentsCheck.class, + EventMandatoryDisplayContextCheck.class, + HtlAttributesShouldBeAtTheEndCheck.class, + InlineStyleMandatoryDisplayContextCheck.class, + NamingAndReusingConditionsCheck.class, + PlaceTemplatesInSeparateFilesCheck.class, + ScriptsAndStyleMandatoryDisplayContextCheck.class, + UseMostRestrictiveHtlContextCheck.class, + UseSlyTagsOverRedundantMarkupCheck.class, + CamelCaseCheck.class, + SlyElementsAreAutomaticallyUnwrappedCheck.class, + ExplicitNamesInLoopsCheck.class + ); + } + + public static Rule getRule(Class clazz) { + return Optional.ofNullable(clazz) + .filter(c -> c.isAnnotationPresent(Rule.class)) + .map(c -> c.getAnnotation(Rule.class)) + .orElse(null); + } +} diff --git a/src/main/java/com/cognifide/aemrules/htl/visitors/DefaultHtlVisitor.java b/src/main/java/com/vml/aemrules/htl/visitors/DefaultHtlVisitor.java similarity index 94% rename from src/main/java/com/cognifide/aemrules/htl/visitors/DefaultHtlVisitor.java rename to src/main/java/com/vml/aemrules/htl/visitors/DefaultHtlVisitor.java index 6a466cc9..88a08923 100644 --- a/src/main/java/com/cognifide/aemrules/htl/visitors/DefaultHtlVisitor.java +++ b/src/main/java/com/vml/aemrules/htl/visitors/DefaultHtlVisitor.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,9 +17,8 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.visitors; +package com.vml.aemrules.htl.visitors; -import java.util.List; import org.apache.sling.scripting.sightly.compiler.expression.Expression; import org.sonar.plugins.html.node.CommentNode; import org.sonar.plugins.html.node.DirectiveNode; @@ -29,6 +28,8 @@ import org.sonar.plugins.html.node.TextNode; import org.sonar.plugins.html.visitor.HtmlSourceCode; +import java.util.List; + public interface DefaultHtlVisitor { default void init() { diff --git a/src/main/java/com/cognifide/aemrules/htl/visitors/HtlScanner.java b/src/main/java/com/vml/aemrules/htl/visitors/HtlScanner.java similarity index 85% rename from src/main/java/com/cognifide/aemrules/htl/visitors/HtlScanner.java rename to src/main/java/com/vml/aemrules/htl/visitors/HtlScanner.java index 8c8a0fa7..64d200db 100644 --- a/src/main/java/com/cognifide/aemrules/htl/visitors/HtlScanner.java +++ b/src/main/java/com/vml/aemrules/htl/visitors/HtlScanner.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,13 +17,8 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.visitors; +package com.vml.aemrules.htl.visitors; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; import org.apache.sling.scripting.sightly.compiler.expression.Expression; import org.apache.sling.scripting.sightly.impl.compiler.Syntax; import org.apache.sling.scripting.sightly.impl.compiler.frontend.ExpressionParser; @@ -38,21 +33,28 @@ import org.sonar.plugins.html.node.TextNode; import org.sonar.plugins.html.visitor.HtmlSourceCode; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + public class HtlScanner { private static final ExpressionParser expressionParser = new ExpressionParser(); private final List checkVisitors = new ArrayList<>(); + private static void scanElementTag(DefaultHtlVisitor visitor, TagNode node) { if (!node.isEndElement()) { visitor.startElement(node); if (isHtlTag(node)) { List expressions = - node.getAttributes().stream() - .map(Attribute::getValue) - .filter(HtlScanner::hasHtlExpression) - .flatMap(HtlScanner::getExpressions) - .collect(Collectors.toList()); + node.getAttributes().stream() + .map(Attribute::getValue) + .filter(HtlScanner::hasHtlExpression) + .flatMap(HtlScanner::getExpressions) + .collect(Collectors.toList()); visitor.startHtlElement(expressions, node); } } @@ -63,8 +65,8 @@ private static void scanElementTag(DefaultHtlVisitor visitor, TagNode node) { private static boolean isHtlTag(TagNode node) { boolean hasDataSlyAttribute = node.getAttributes().stream() - .map(Attribute::getName) - .anyMatch(Syntax::isPluginAttribute); + .map(Attribute::getName) + .anyMatch(Syntax::isPluginAttribute); boolean isSlyTag = "sly".equalsIgnoreCase(node.getNodeName()); return isSlyTag || hasDataSlyAttribute; } @@ -72,15 +74,15 @@ private static boolean isHtlTag(TagNode node) { private static Stream getExpressions(String code) { Interpolation interpolation = expressionParser.parseInterpolation(code); return StreamSupport - .stream(interpolation.getFragments().spliterator(), false) - .filter(Fragment::isExpression) - .map(Fragment::getExpression); + .stream(interpolation.getFragments().spliterator(), false) + .filter(Fragment::isExpression) + .map(Fragment::getExpression); } private static boolean hasHtlExpression(String code) { return getExpressions(code) - .findAny() - .isPresent(); + .findAny() + .isPresent(); } /** @@ -99,7 +101,7 @@ public void scan(List nodeList, HtmlSourceCode htmlSourceCode) { } private void scan(List nodeList, HtmlSourceCode htmlSourceCode, - List visitors) { + List visitors) { // prepare the visitors for (DefaultHtlVisitor visitor : visitors) { visitor.setSourceCode(htmlSourceCode); @@ -152,7 +154,7 @@ private void scanElement(DefaultHtlVisitor visitor, Node node) { if (hasHtlExpression(node.getCode())) { getExpressions(node.getCode()) - .forEach(expression -> visitor.htlExpression(expression, node)); + .forEach(expression -> visitor.htlExpression(expression, node)); } } diff --git a/src/main/java/com/cognifide/aemrules/htl/visitors/HtlStringOptionVisitor.java b/src/main/java/com/vml/aemrules/htl/visitors/HtlStringOptionVisitor.java similarity index 68% rename from src/main/java/com/cognifide/aemrules/htl/visitors/HtlStringOptionVisitor.java rename to src/main/java/com/vml/aemrules/htl/visitors/HtlStringOptionVisitor.java index 3514ec95..afada7d4 100644 --- a/src/main/java/com/cognifide/aemrules/htl/visitors/HtlStringOptionVisitor.java +++ b/src/main/java/com/vml/aemrules/htl/visitors/HtlStringOptionVisitor.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,22 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.visitors; +package com.vml.aemrules.htl.visitors; import org.apache.commons.lang3.StringUtils; import org.apache.sling.scripting.sightly.compiler.expression.NodeVisitor; -import org.apache.sling.scripting.sightly.compiler.expression.nodes.*; +import org.apache.sling.scripting.sightly.compiler.expression.nodes.ArrayLiteral; +import org.apache.sling.scripting.sightly.compiler.expression.nodes.BinaryOperation; +import org.apache.sling.scripting.sightly.compiler.expression.nodes.BooleanConstant; +import org.apache.sling.scripting.sightly.compiler.expression.nodes.Identifier; +import org.apache.sling.scripting.sightly.compiler.expression.nodes.MapLiteral; +import org.apache.sling.scripting.sightly.compiler.expression.nodes.NullLiteral; +import org.apache.sling.scripting.sightly.compiler.expression.nodes.NumericConstant; +import org.apache.sling.scripting.sightly.compiler.expression.nodes.PropertyAccess; +import org.apache.sling.scripting.sightly.compiler.expression.nodes.RuntimeCall; +import org.apache.sling.scripting.sightly.compiler.expression.nodes.StringConstant; +import org.apache.sling.scripting.sightly.compiler.expression.nodes.TernaryOperator; +import org.apache.sling.scripting.sightly.compiler.expression.nodes.UnaryOperation; public class HtlStringOptionVisitor implements NodeVisitor { @Override diff --git a/src/main/java/com/cognifide/aemrules/java/Constants.java b/src/main/java/com/vml/aemrules/java/Constants.java similarity index 82% rename from src/main/java/com/cognifide/aemrules/java/Constants.java rename to src/main/java/com/vml/aemrules/java/Constants.java index 72d4e6f3..27d41b04 100644 --- a/src/main/java/com/cognifide/aemrules/java/Constants.java +++ b/src/main/java/com/vml/aemrules/java/Constants.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,13 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java; +package com.vml.aemrules.java; public final class Constants { + public static final String REPOSITORY_KEY = "AEM-JAVA"; + public static final String REPOSITORY_NAME = "AEM Java"; + public static final String SLING_RESOURCE_QUALIFIED_NAME = "org.apache.sling.api.resource.Resource"; private Constants() { diff --git a/src/main/java/com/cognifide/aemrules/java/checks/AdministrativeAccessUsageCheck.java b/src/main/java/com/vml/aemrules/java/checks/AdministrativeAccessUsageCheck.java similarity index 61% rename from src/main/java/com/cognifide/aemrules/java/checks/AdministrativeAccessUsageCheck.java rename to src/main/java/com/vml/aemrules/java/checks/AdministrativeAccessUsageCheck.java index b0b17bfd..0a31849d 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/AdministrativeAccessUsageCheck.java +++ b/src/main/java/com/vml/aemrules/java/checks/AdministrativeAccessUsageCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,15 +17,19 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; +package com.vml.aemrules.java.checks; -import com.cognifide.aemrules.matcher.MethodMatcher; -import com.cognifide.aemrules.matcher.MethodNamePredicate; -import com.cognifide.aemrules.matcher.OwnerTypePredicate; -import com.cognifide.aemrules.matcher.ParameterTypePredicate; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; +import com.vml.aemrules.matcher.MethodMatcher; +import com.vml.aemrules.matcher.MethodNamePredicate; +import com.vml.aemrules.matcher.OwnerTypePredicate; +import com.vml.aemrules.matcher.ParameterTypePredicate; +import com.vml.aemrules.version.AemVersion; +import org.sonar.check.Rule; +import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; +import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; +import org.sonar.plugins.java.api.tree.MethodInvocationTree; +import org.sonar.plugins.java.api.tree.Tree; +import org.sonar.plugins.java.api.tree.Tree.Kind; import java.util.AbstractMap; import java.util.Arrays; @@ -33,26 +37,9 @@ import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.sonar.check.Priority; -import org.sonar.check.Rule; -import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; -import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; -import org.sonar.plugins.java.api.tree.MethodInvocationTree; -import org.sonar.plugins.java.api.tree.Tree; -import org.sonar.plugins.java.api.tree.Tree.Kind; -@Rule( - key = AdministrativeAccessUsageCheck.RULE_KEY, - name = AdministrativeAccessUsageCheck.RULE_MESSAGE, - priority = Priority.MAJOR, - tags = Tags.AEM -) -@AemVersion( - from = "6.0" -) -@Metadata( - technicalDebt = "30min" -) +@Rule(key = AdministrativeAccessUsageCheck.RULE_KEY) +@AemVersion(from = "6.0") public class AdministrativeAccessUsageCheck extends IssuableSubscriptionVisitor { public static final String RULE_KEY = "AEM-11"; @@ -60,24 +47,24 @@ public class AdministrativeAccessUsageCheck extends IssuableSubscriptionVisitor public static final String RULE_MESSAGE = "Do not use deprecated administrative access methods"; private static final Map SUBSTITUTES = Stream.of( - new AbstractMap.SimpleImmutableEntry<>("loginAdministrative", "loginService"), - new AbstractMap.SimpleImmutableEntry<>("getAdministrativeResourceResolver", "getServiceResourceResolver") + new AbstractMap.SimpleImmutableEntry<>("loginAdministrative", "loginService"), + new AbstractMap.SimpleImmutableEntry<>("getAdministrativeResourceResolver", "getServiceResourceResolver") ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); private static final List matchers = Arrays.asList( - MethodMatcher.create( - MethodNamePredicate.is("loginAdministrative"), - OwnerTypePredicate.is("org.apache.sling.jcr.api.SlingRepository"), - ParameterTypePredicate.is("java.lang.String")), - MethodMatcher.create( - MethodNamePredicate.is("getAdministrativeResourceResolver"), - OwnerTypePredicate.is("org.apache.sling.api.resource.ResourceResolverFactory"), - ParameterTypePredicate.is("java.util.Map")) + MethodMatcher.create( + MethodNamePredicate.is("loginAdministrative"), + OwnerTypePredicate.is("org.apache.sling.jcr.api.SlingRepository"), + ParameterTypePredicate.is("java.lang.String")), + MethodMatcher.create( + MethodNamePredicate.is("getAdministrativeResourceResolver"), + OwnerTypePredicate.is("org.apache.sling.api.resource.ResourceResolverFactory"), + ParameterTypePredicate.is("java.util.Map")) ); @Override - public List nodesToVisit() { - return Arrays.asList(Tree.Kind.METHOD_INVOCATION); + public List nodesToVisit() { + return List.of(Kind.METHOD_INVOCATION); } @Override diff --git a/src/main/java/com/cognifide/aemrules/java/checks/AnnotationsConstantsCheck.java b/src/main/java/com/vml/aemrules/java/checks/AnnotationsConstantsCheck.java similarity index 75% rename from src/main/java/com/cognifide/aemrules/java/checks/AnnotationsConstantsCheck.java rename to src/main/java/com/vml/aemrules/java/checks/AnnotationsConstantsCheck.java index 9225becc..06721772 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/AnnotationsConstantsCheck.java +++ b/src/main/java/com/vml/aemrules/java/checks/AnnotationsConstantsCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,14 +17,11 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; +package com.vml.aemrules.java.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.java.util.ConstantsChecker; -import com.cognifide.aemrules.version.AemVersion; +import com.vml.aemrules.java.util.ConstantsChecker; +import com.vml.aemrules.version.AemVersion; import org.apache.commons.lang3.StringUtils; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.JavaFileScanner; import org.sonar.plugins.java.api.JavaFileScannerContext; @@ -33,18 +30,8 @@ import org.sonar.plugins.java.api.tree.LiteralTree; import org.sonar.plugins.java.api.tree.Tree.Kind; -@Rule( - key = AnnotationsConstantsCheck.RULE_KEY, - name = AnnotationsConstantsCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - all = true -) -@Metadata( - technicalDebt = "5min" -) +@Rule(key = AnnotationsConstantsCheck.RULE_KEY) +@AemVersion(all = true) public class AnnotationsConstantsCheck extends BaseTreeVisitor implements JavaFileScanner { public static final String RULE_KEY = "AEM-1"; @@ -74,7 +61,7 @@ public void visitLiteral(LiteralTree tree) { String literalValue = removeQuotes(tree.value()); if (ConstantsChecker.isAnnotationConstant(literalValue)) { context.reportIssue(this, tree, - String.format("Use constant %s instead of hardcoded value.", ConstantsChecker.getAnnotationMessageForConstant(literalValue))); + String.format("Use constant %s instead of hardcoded value.", ConstantsChecker.getAnnotationMessageForConstant(literalValue))); } } super.visitLiteral(tree); diff --git a/src/main/java/com/cognifide/aemrules/java/checks/ConstantsCheck.java b/src/main/java/com/vml/aemrules/java/checks/ConstantsCheck.java similarity index 74% rename from src/main/java/com/cognifide/aemrules/java/checks/ConstantsCheck.java rename to src/main/java/com/vml/aemrules/java/checks/ConstantsCheck.java index e7d75ce7..78f0bcc6 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/ConstantsCheck.java +++ b/src/main/java/com/vml/aemrules/java/checks/ConstantsCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,35 +17,21 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; +package com.vml.aemrules.java.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.java.util.ConstantsChecker; -import com.cognifide.aemrules.version.AemVersion; - -import java.util.Arrays; -import java.util.List; +import com.vml.aemrules.java.util.ConstantsChecker; +import com.vml.aemrules.version.AemVersion; import org.apache.commons.lang3.StringUtils; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.LiteralTree; import org.sonar.plugins.java.api.tree.Tree; import org.sonar.plugins.java.api.tree.Tree.Kind; -@Rule( - key = ConstantsCheck.RULE_KEY, - name = ConstantsCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - all = true -) -@Metadata( - technicalDebt = "5min" -) +import java.util.List; + +@Rule(key = ConstantsCheck.RULE_KEY) +@AemVersion(all = true) public class ConstantsCheck extends IssuableSubscriptionVisitor { public static final String RULE_MESSAGE = "Use predefined constant instead of hardcoded value."; @@ -54,7 +40,7 @@ public class ConstantsCheck extends IssuableSubscriptionVisitor { @Override public List nodesToVisit() { - return Arrays.asList(Kind.STRING_LITERAL); + return List.of(Kind.STRING_LITERAL); } @Override diff --git a/src/main/java/com/cognifide/aemrules/java/checks/ContentResourceShouldBeNullCheckedCheck.java b/src/main/java/com/vml/aemrules/java/checks/ContentResourceShouldBeNullCheckedCheck.java similarity index 85% rename from src/main/java/com/cognifide/aemrules/java/checks/ContentResourceShouldBeNullCheckedCheck.java rename to src/main/java/com/vml/aemrules/java/checks/ContentResourceShouldBeNullCheckedCheck.java index 2c98980b..1f226594 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/ContentResourceShouldBeNullCheckedCheck.java +++ b/src/main/java/com/vml/aemrules/java/checks/ContentResourceShouldBeNullCheckedCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,18 +17,10 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; +package com.vml.aemrules.java.checks; -import static org.sonar.plugins.java.api.tree.Tree.Kind.EQUAL_TO; -import static org.sonar.plugins.java.api.tree.Tree.Kind.NOT_EQUAL_TO; - -import com.cognifide.aemrules.java.Constants; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import java.util.HashMap; -import java.util.Map; -import org.sonar.check.Priority; +import com.vml.aemrules.java.Constants; +import com.vml.aemrules.version.AemVersion; import org.sonar.check.Rule; import org.sonar.plugins.java.api.JavaFileScanner; import org.sonar.plugins.java.api.JavaFileScannerContext; @@ -46,18 +38,14 @@ import org.sonar.plugins.java.api.tree.Tree.Kind; import org.sonar.plugins.java.api.tree.VariableTree; -@Rule( - key = ContentResourceShouldBeNullCheckedCheck.RULE_KEY, - name = ContentResourceShouldBeNullCheckedCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - all = true -) -@Metadata( - technicalDebt = "5min" -) +import java.util.HashMap; +import java.util.Map; + +import static org.sonar.plugins.java.api.tree.Tree.Kind.EQUAL_TO; +import static org.sonar.plugins.java.api.tree.Tree.Kind.NOT_EQUAL_TO; + +@Rule(key = ContentResourceShouldBeNullCheckedCheck.RULE_KEY) +@AemVersion(all = true) public class ContentResourceShouldBeNullCheckedCheck extends BaseTreeVisitor implements JavaFileScanner { public static final String RULE_KEY = "AEM-18"; @@ -75,17 +63,12 @@ public class ContentResourceShouldBeNullCheckedCheck extends BaseTreeVisitor imp private static final String IS_NULL_METHOD = "isNull"; private static final int METHOD_FIRST_ARGUMENT = 0; - + private final Map contentResources = new HashMap<>(); private boolean returnOccurredInsideEqualNullCheck = false; - private boolean insideEqualNullCheck = false; - private boolean insideIfStatement = false; - private JavaFileScannerContext context; - private Map contentResources = new HashMap(); - @Override public void scanFile(JavaFileScannerContext context) { this.context = context; @@ -160,7 +143,7 @@ private void cleanFlagsAfterIfStatement(IfStatementTree tree) { private void equalsNullCheck(MethodInvocationTree tree) { Boolean firstTokenText = contentResources.getOrDefault(tree.firstToken().text(), true); if (Boolean.FALSE.equals(firstTokenText) && - !returnOccurredInsideEqualNullCheck) { + !returnOccurredInsideEqualNullCheck) { context.reportIssue(this, tree, RULE_MESSAGE); } } @@ -186,10 +169,10 @@ private void chainedMethodsNullCheck(MethodInvocationTree tree) { MemberSelectExpressionTree method = (MemberSelectExpressionTree) tree.methodSelect(); if (method.expression() instanceof MethodInvocationTree) { MethodInvocationTree invocation = (MethodInvocationTree) method.expression(); - if (!invocation.symbol().isUnknown() && - isPage(invocation.symbol().owner().type().fullyQualifiedName()) && - isGetContentResourceUsedOnPage(invocation) && - !returnOccurredInsideEqualNullCheck) { + if (!invocation.methodSymbol().isUnknown() && + isPage(invocation.methodSymbol().owner().type().fullyQualifiedName()) && + isGetContentResourceUsedOnPage(invocation) && + !returnOccurredInsideEqualNullCheck) { context.reportIssue(this, tree, RULE_MESSAGE); } } @@ -210,16 +193,16 @@ private boolean isGetContentResourceUsedOnPage(MethodInvocationTree tree) { private boolean isGetContentResourceUsedOnPage(VariableTree tree) { return tree.initializer() instanceof MethodInvocationTree && - !((MethodInvocationTree) tree.initializer()).symbol().isUnknown() && - isPage(((MethodInvocationTree) tree.initializer()).symbol().owner().type() - .fullyQualifiedName()) && - GET_CONTENT_RESOURCE_METHOD.equals(((MethodInvocationTree) tree.initializer()).symbol().name()); + !((MethodInvocationTree) tree.initializer()).methodSymbol().isUnknown() && + isPage(((MethodInvocationTree) tree.initializer()).methodSymbol().owner().type() + .fullyQualifiedName()) && + GET_CONTENT_RESOURCE_METHOD.equals(((MethodInvocationTree) tree.initializer()).methodSymbol().name()); } private boolean isGetContentResourceUsedOnResource(AssignmentExpressionTree tree) { return isResource(tree) && - tree.expression() instanceof MethodInvocationTree && - GET_CONTENT_RESOURCE_METHOD.equals(((MethodInvocationTree) tree.expression()).symbol().name()); + tree.expression() instanceof MethodInvocationTree && + GET_CONTENT_RESOURCE_METHOD.equals(((MethodInvocationTree) tree.expression()).methodSymbol().name()); } private boolean isPage(String name) { @@ -255,7 +238,7 @@ private boolean isNullLiteral(Tree operand) { private boolean isResourceType(Tree operand) { return operand instanceof IdentifierTree && Constants.SLING_RESOURCE_QUALIFIED_NAME - .equals(((IdentifierTree) operand).symbolType().fullyQualifiedName()); + .equals(((IdentifierTree) operand).symbolType().fullyQualifiedName()); } private boolean isNonNullUsed(MethodInvocationTree tree) { diff --git a/src/main/java/com/cognifide/aemrules/java/checks/ModifiableValueMapUsageCheck.java b/src/main/java/com/vml/aemrules/java/checks/ModifiableValueMapUsageCheck.java similarity index 87% rename from src/main/java/com/cognifide/aemrules/java/checks/ModifiableValueMapUsageCheck.java rename to src/main/java/com/vml/aemrules/java/checks/ModifiableValueMapUsageCheck.java index 9be25198..5c741802 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/ModifiableValueMapUsageCheck.java +++ b/src/main/java/com/vml/aemrules/java/checks/ModifiableValueMapUsageCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,9 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; +package com.vml.aemrules.java.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.sonar.check.Priority; +import com.vml.aemrules.version.AemVersion; import org.sonar.check.Rule; import org.sonar.plugins.java.api.JavaFileScanner; import org.sonar.plugins.java.api.JavaFileScannerContext; @@ -40,18 +32,13 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonar.plugins.java.api.tree.VariableTree; -@Rule( - key = ModifiableValueMapUsageCheck.RULE_KEY, - name = ModifiableValueMapUsageCheck.RULE_MESSAGE, - priority = Priority.CRITICAL, - tags = Tags.AEM -) -@AemVersion( - all = true -) -@Metadata( - technicalDebt = "10min" -) +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Rule(key = ModifiableValueMapUsageCheck.RULE_KEY) +@AemVersion(all = true) public class ModifiableValueMapUsageCheck extends BaseTreeVisitor implements JavaFileScanner { protected static final String RULE_KEY = "AEM-17"; @@ -61,9 +48,9 @@ public class ModifiableValueMapUsageCheck extends BaseTreeVisitor implements Jav private static final String MODIFIABLE_VALUE_MAP_FULL_NAME = "org.apache.sling.api.resource.ModifiableValueMap"; private static final Set MUTABLE_METHODS = Stream.of( - "put", - "putAll", - "remove" + "put", + "putAll", + "remove" ).collect(Collectors.toSet()); private JavaFileScannerContext context; @@ -111,7 +98,7 @@ private void visitMethodWithMVM(IdentifierTree modifiableValueMapUsageIdentifier int argumentNumber = ((Arguments) usageOfMVM).indexOf(modifiableValueMapUsageIdentifier); MethodInvocationTree methodInvocationWithMVM = (MethodInvocationTree) usageOfMVM.parent(); if (methodInvocationWithMVM != null) { - MethodTree methodWithMVM = (MethodTree) methodInvocationWithMVM.symbol().declaration(); + MethodTree methodWithMVM = methodInvocationWithMVM.methodSymbol().declaration(); if (methodWithMVM != null && methodWithMVM.is(Tree.Kind.METHOD)) { MethodWithMVMVisitor methodWithMVMVisitor = new MethodWithMVMVisitor(this, argumentNumber); methodWithMVM.accept(methodWithMVMVisitor); @@ -141,4 +128,4 @@ public void visitMethod(MethodTree tree) { } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cognifide/aemrules/java/checks/PreferSlingServletAnnotation.java b/src/main/java/com/vml/aemrules/java/checks/PreferSlingServletAnnotation.java similarity index 90% rename from src/main/java/com/cognifide/aemrules/java/checks/PreferSlingServletAnnotation.java rename to src/main/java/com/vml/aemrules/java/checks/PreferSlingServletAnnotation.java index fbb8aee0..70581e3b 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/PreferSlingServletAnnotation.java +++ b/src/main/java/com/vml/aemrules/java/checks/PreferSlingServletAnnotation.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,21 +17,10 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; - -import static org.sonar.plugins.java.api.tree.Tree.Kind.IDENTIFIER; -import static org.sonar.plugins.java.api.tree.Tree.Kind.MEMBER_SELECT; -import static org.sonar.plugins.java.api.tree.Tree.Kind.STRING_LITERAL; - -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; +package com.vml.aemrules.java.checks; +import com.vml.aemrules.version.AemVersion; import org.apache.commons.lang3.StringUtils; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.JavaFileScanner; import org.sonar.plugins.java.api.JavaFileScannerContext; @@ -46,18 +35,18 @@ import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; import org.sonar.plugins.java.api.tree.Tree; -@Rule( - key = PreferSlingServletAnnotation.RULE_KEY, - name = PreferSlingServletAnnotation.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.sonar.plugins.java.api.tree.Tree.Kind.IDENTIFIER; +import static org.sonar.plugins.java.api.tree.Tree.Kind.MEMBER_SELECT; +import static org.sonar.plugins.java.api.tree.Tree.Kind.STRING_LITERAL; + +@Rule(key = PreferSlingServletAnnotation.RULE_KEY) @AemVersion( - from = "6.0", - to = "6.2" -) -@Metadata( - technicalDebt = "10min" + from = "6.0", + to = "6.2" ) public class PreferSlingServletAnnotation extends BaseTreeVisitor implements JavaFileScanner { @@ -72,17 +61,17 @@ public class PreferSlingServletAnnotation extends BaseTreeVisitor implements Jav public static final String NAME = "name"; private static final Set SERVLET_CONSTANTS = Stream.of( - "SLING_SERVLET_METHODS", - "SLING_SERVLET_EXTENSIONS", - "SLING_SERVLET_SELECTORS", - "SLING_SERVLET_RESOURCE_TYPES" + "SLING_SERVLET_METHODS", + "SLING_SERVLET_EXTENSIONS", + "SLING_SERVLET_SELECTORS", + "SLING_SERVLET_RESOURCE_TYPES" ).collect(Collectors.toSet()); private static final Set SERVLET_CONSTANTS_VALUES = Stream.of( - "sling.servlet.paths", - "sling.servlet.resourceTypes", - "sling.servlet.selectors", - "sling.servlet.extensions" + "sling.servlet.paths", + "sling.servlet.resourceTypes", + "sling.servlet.selectors", + "sling.servlet.extensions" ).collect(Collectors.toSet()); private JavaFileScannerContext context; diff --git a/src/main/java/com/cognifide/aemrules/java/checks/SessionShouldBeLoggedOut.java b/src/main/java/com/vml/aemrules/java/checks/SessionShouldBeLoggedOut.java similarity index 85% rename from src/main/java/com/cognifide/aemrules/java/checks/SessionShouldBeLoggedOut.java rename to src/main/java/com/vml/aemrules/java/checks/SessionShouldBeLoggedOut.java index 02e32227..368fb6e1 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/SessionShouldBeLoggedOut.java +++ b/src/main/java/com/vml/aemrules/java/checks/SessionShouldBeLoggedOut.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,19 +17,12 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; - -import com.cognifide.aemrules.java.checks.visitors.CheckLoggedOutVisitor; -import com.cognifide.aemrules.java.checks.visitors.FinallyBlockVisitor; -import com.cognifide.aemrules.java.checks.visitors.FindSessionDeclarationVisitor; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import org.sonar.check.Priority; +package com.vml.aemrules.java.checks; + +import com.vml.aemrules.java.checks.visitors.CheckLoggedOutVisitor; +import com.vml.aemrules.java.checks.visitors.FinallyBlockVisitor; +import com.vml.aemrules.java.checks.visitors.FindSessionDeclarationVisitor; +import com.vml.aemrules.version.AemVersion; import org.sonar.check.Rule; import org.sonar.plugins.java.api.JavaFileScanner; import org.sonar.plugins.java.api.JavaFileScannerContext; @@ -40,18 +33,13 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonar.plugins.java.api.tree.VariableTree; -@Rule( - key = SessionShouldBeLoggedOut.RULE_KEY, - name = SessionShouldBeLoggedOut.RULE_MESSAGE, - priority = Priority.CRITICAL, - tags = Tags.AEM -) -@AemVersion( - all = true -) -@Metadata( - technicalDebt = "10min" -) +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +@Rule(key = SessionShouldBeLoggedOut.RULE_KEY) +@AemVersion(all = true) public class SessionShouldBeLoggedOut extends BaseTreeVisitor implements JavaFileScanner { public static final String RULE_KEY = "AEM-7"; diff --git a/src/main/java/com/cognifide/aemrules/java/checks/SynchronizedKeywordUsageCheck.java b/src/main/java/com/vml/aemrules/java/checks/SynchronizedKeywordUsageCheck.java similarity index 71% rename from src/main/java/com/cognifide/aemrules/java/checks/SynchronizedKeywordUsageCheck.java rename to src/main/java/com/vml/aemrules/java/checks/SynchronizedKeywordUsageCheck.java index 3ce5c9e4..93bddd4e 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/SynchronizedKeywordUsageCheck.java +++ b/src/main/java/com/vml/aemrules/java/checks/SynchronizedKeywordUsageCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,9 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; +package com.vml.aemrules.java.checks; -import static com.cognifide.aemrules.java.checks.SynchronizedKeywordUsageCheck.DESCRIPTION; - -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; - -import java.util.Arrays; -import java.util.List; -import org.sonar.check.Priority; +import com.vml.aemrules.version.AemVersion; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.BaseTreeVisitor; @@ -37,31 +29,21 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonar.plugins.java.api.tree.Tree.Kind; -@Rule( - key = SynchronizedKeywordUsageCheck.RULE_KEY, - name = SynchronizedKeywordUsageCheck.MESSAGE, - description = DESCRIPTION, - priority = Priority.INFO, - tags = {Tags.MULTI_THREADING, Tags.PERFORMANCE} -) -@AemVersion( - all = true -) -@Metadata( - technicalDebt = "30min" -) -public class SynchronizedKeywordUsageCheck extends IssuableSubscriptionVisitor { +import java.util.Arrays; +import java.util.List; - protected static final String MESSAGE = "Usage of 'synchronized' keyword should be avoided if possible."; +@Rule(key = SynchronizedKeywordUsageCheck.RULE_KEY) +@AemVersion(all = true) +public class SynchronizedKeywordUsageCheck extends IssuableSubscriptionVisitor { protected static final String RULE_KEY = "AEM-15"; - protected static final String DESCRIPTION = "Check if using 'synchronized' can be replaced with more sophisticated solution."; + protected static final String MESSAGE = "Usage of 'synchronized' keyword should be avoided if possible."; - private static final List ACCEPTED_NODE_KINDS = Arrays.asList(Kind.SYNCHRONIZED_STATEMENT, Kind.METHOD); + private static final List ACCEPTED_NODE_KINDS = Arrays.asList(Kind.SYNCHRONIZED_STATEMENT, Kind.METHOD); @Override - public List nodesToVisit() { + public List nodesToVisit() { return ACCEPTED_NODE_KINDS; } diff --git a/src/main/java/com/cognifide/aemrules/java/checks/ThreadSafeFieldCheck.java b/src/main/java/com/vml/aemrules/java/checks/ThreadSafeFieldCheck.java similarity index 72% rename from src/main/java/com/cognifide/aemrules/java/checks/ThreadSafeFieldCheck.java rename to src/main/java/com/vml/aemrules/java/checks/ThreadSafeFieldCheck.java index 272967c4..960b5b96 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/ThreadSafeFieldCheck.java +++ b/src/main/java/com/vml/aemrules/java/checks/ThreadSafeFieldCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,18 +17,9 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; +package com.vml.aemrules.java.checks; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; - -import java.util.Collections; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.sonar.check.Priority; +import com.vml.aemrules.version.AemVersion; import org.sonar.check.Rule; import org.sonar.plugins.java.api.JavaFileScanner; import org.sonar.plugins.java.api.JavaFileScannerContext; @@ -40,21 +31,14 @@ import org.sonar.plugins.java.api.tree.TypeTree; import org.sonar.plugins.java.api.tree.VariableTree; -@Rule( - key = ThreadSafeFieldCheck.RULE_KEY, - name = ThreadSafeFieldCheck.RULE_NAME, - priority = Priority.CRITICAL, - tags = {Tags.BUG, Tags.AEM} -) -@AemVersion( - all = true -) -@Metadata( - technicalDebt = "1h" -) -public class ThreadSafeFieldCheck extends BaseTreeVisitor implements JavaFileScanner { +import java.util.Collections; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; - public static final String RULE_NAME = "Non-thread safe object used as a field of Servlet / Filter etc."; +@Rule(key = ThreadSafeFieldCheck.RULE_KEY) +@AemVersion(all = true) +public class ThreadSafeFieldCheck extends BaseTreeVisitor implements JavaFileScanner { public static final String RULE_KEY = "AEM-3"; @@ -63,30 +47,30 @@ public class ThreadSafeFieldCheck extends BaseTreeVisitor implements JavaFileSca private static final Set VULNERABLE_CLASSES = Collections.emptySet(); // empty for now private static final Set VULNERABLE_INTERFACES = Stream.of( - "javax.servlet.Servlet", - "javax.servlet.Filter", - "org.osgi.service.event.EventHandler" + "javax.servlet.Servlet", + "javax.servlet.Filter", + "org.osgi.service.event.EventHandler" ).collect(Collectors.toSet()); private static final Set VULNERABLE_ANNOTATIONS = Stream.of( - "org.apache.felix.scr.annotations.Component", - "org.osgi.service.component.annotations.Component", - "org.apache.felix.scr.annotations.sling.SlingServlet", // this is possibly duplicative, but that shouldn't be a problem. - "org.apache.felix.scr.annotations.sling.SlingFilter" // this is possibly duplicative, but that shouldn't be a problem. + "org.apache.felix.scr.annotations.Component", + "org.osgi.service.component.annotations.Component", + "org.apache.felix.scr.annotations.sling.SlingServlet", // this is possibly duplicative, but that shouldn't be a problem. + "org.apache.felix.scr.annotations.sling.SlingFilter" // this is possibly duplicative, but that shouldn't be a problem. ).collect(Collectors.toSet()); private static final Set NON_THREAD_SAFE_TYPES = Stream.of( - "org.apache.sling.api.resource.ResourceResolver", - "javax.jcr.Session", - "com.day.cq.wcm.api.PageManager", - "com.day.cq.wcm.api.components.ComponentManager", - "com.day.cq.wcm.api.designer.Designer", - "com.day.cq.dam.api.AssetManager", - "com.day.cq.tagging.TagManager", - "com.day.cq.security.UserManager", - "org.apache.jackrabbit.api.security.user.Authorizable", - "org.apache.jackrabbit.api.security.user.User", - "org.apache.jackrabbit.api.security.user.UserManager" + "org.apache.sling.api.resource.ResourceResolver", + "javax.jcr.Session", + "com.day.cq.wcm.api.PageManager", + "com.day.cq.wcm.api.components.ComponentManager", + "com.day.cq.wcm.api.designer.Designer", + "com.day.cq.dam.api.AssetManager", + "com.day.cq.tagging.TagManager", + "com.day.cq.security.UserManager", + "org.apache.jackrabbit.api.security.user.Authorizable", + "org.apache.jackrabbit.api.security.user.User", + "org.apache.jackrabbit.api.security.user.UserManager" ).collect(Collectors.toSet()); private JavaFileScannerContext context; diff --git a/src/main/java/com/cognifide/aemrules/java/checks/resourceresolver/close/FindRRDeclarationVisitor.java b/src/main/java/com/vml/aemrules/java/checks/resourceresolver/close/FindRRDeclarationVisitor.java similarity index 94% rename from src/main/java/com/cognifide/aemrules/java/checks/resourceresolver/close/FindRRDeclarationVisitor.java rename to src/main/java/com/vml/aemrules/java/checks/resourceresolver/close/FindRRDeclarationVisitor.java index 9924b7b6..9b0971cb 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/resourceresolver/close/FindRRDeclarationVisitor.java +++ b/src/main/java/com/vml/aemrules/java/checks/resourceresolver/close/FindRRDeclarationVisitor.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks.resourceresolver.close; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; +package com.vml.aemrules.java.checks.resourceresolver.close; import org.sonar.plugins.java.api.semantic.Symbol; import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; @@ -35,6 +31,10 @@ import org.sonar.plugins.java.api.tree.TryStatementTree; import org.sonar.plugins.java.api.tree.VariableTree; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + /** * Finds all injector variable declarations. Used in method's bodies only. Works only for declaration within the same file - api limitations: {@link * Symbol#declaration()} @@ -112,14 +112,14 @@ public void visitReturnStatement(ReturnStatementTree tree) { IdentifierTree identifier = (IdentifierTree) tree.expression(); Tree declaration = identifier.symbol().declaration(); if (resourceResolvers.contains(declaration)) { - resourceResolvers.remove(declaration); + resourceResolvers.remove(declaration); } } super.visitReturnStatement(tree); } private boolean isRRF(MethodInvocationTree invocationTree) { - return invocationTree.symbol().owner().type().fullyQualifiedName().equals(RESOURCE_RESOLVER_FACTORY); + return invocationTree.methodSymbol().owner().type().fullyQualifiedName().equals(RESOURCE_RESOLVER_FACTORY); } private boolean isResourceResolver(MethodInvocationTree invocationTree) { @@ -188,12 +188,12 @@ private boolean isAMethodInvocation(VariableTree tree) { private boolean variableIsEqualToReturnedVariableIn(AssignmentExpressionTree tree) { return tree.variable().is(Kind.IDENTIFIER) - && getDeclaration((IdentifierTree) tree.variable()).equals(declarationOfReturnedVariable); + && getDeclaration((IdentifierTree) tree.variable()).equals(declarationOfReturnedVariable); } private boolean variableIsEqualToReturnedVariableIn(VariableTree tree) { return tree.is(Kind.VARIABLE) - && getDeclarationFromVariable(tree).equals(declarationOfReturnedVariable); + && getDeclarationFromVariable(tree).equals(declarationOfReturnedVariable); } private Tree getDeclarationFromVariable(VariableTree variable) { diff --git a/src/main/java/com/cognifide/aemrules/java/checks/resourceresolver/close/ResourceResolverShouldBeClosed.java b/src/main/java/com/vml/aemrules/java/checks/resourceresolver/close/ResourceResolverShouldBeClosed.java similarity index 86% rename from src/main/java/com/cognifide/aemrules/java/checks/resourceresolver/close/ResourceResolverShouldBeClosed.java rename to src/main/java/com/vml/aemrules/java/checks/resourceresolver/close/ResourceResolverShouldBeClosed.java index f278f87d..2e09b020 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/resourceresolver/close/ResourceResolverShouldBeClosed.java +++ b/src/main/java/com/vml/aemrules/java/checks/resourceresolver/close/ResourceResolverShouldBeClosed.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,18 +17,11 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks.resourceresolver.close; +package com.vml.aemrules.java.checks.resourceresolver.close; -import com.cognifide.aemrules.java.checks.visitors.CheckClosedVisitor; -import com.cognifide.aemrules.java.checks.visitors.FinallyBlockVisitor; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import org.sonar.check.Priority; +import com.vml.aemrules.java.checks.visitors.CheckClosedVisitor; +import com.vml.aemrules.java.checks.visitors.FinallyBlockVisitor; +import com.vml.aemrules.version.AemVersion; import org.sonar.check.Rule; import org.sonar.plugins.java.api.JavaFileScanner; import org.sonar.plugins.java.api.JavaFileScannerContext; @@ -39,18 +32,13 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonar.plugins.java.api.tree.VariableTree; -@Rule( - key = ResourceResolverShouldBeClosed.RULE_KEY, - name = ResourceResolverShouldBeClosed.RULE_MESSAGE, - priority = Priority.CRITICAL, - tags = Tags.AEM -) -@AemVersion( - all = true -) -@Metadata( - technicalDebt = "15min" -) +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +@Rule(key = ResourceResolverShouldBeClosed.RULE_KEY) +@AemVersion(all = true) public class ResourceResolverShouldBeClosed extends BaseTreeVisitor implements JavaFileScanner { public static final String RULE_KEY = "AEM-6"; diff --git a/src/main/java/com/vml/aemrules/java/checks/resourceresolver/close/ResourceResolverTryWithResourcesCheck.java b/src/main/java/com/vml/aemrules/java/checks/resourceresolver/close/ResourceResolverTryWithResourcesCheck.java new file mode 100644 index 00000000..e4b24268 --- /dev/null +++ b/src/main/java/com/vml/aemrules/java/checks/resourceresolver/close/ResourceResolverTryWithResourcesCheck.java @@ -0,0 +1,111 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.java.checks.resourceresolver.close; + +import com.vml.aemrules.version.AemVersion; +import org.sonar.check.Rule; +import org.sonar.plugins.java.api.JavaFileScanner; +import org.sonar.plugins.java.api.JavaFileScannerContext; +import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; +import org.sonar.plugins.java.api.tree.BaseTreeVisitor; +import org.sonar.plugins.java.api.tree.LambdaExpressionTree; +import org.sonar.plugins.java.api.tree.TryStatementTree; +import org.sonar.plugins.java.api.tree.VariableTree; + +import java.util.ArrayList; +import java.util.List; + +@Rule(key = ResourceResolverTryWithResourcesCheck.RULE_KEY) +@AemVersion(all = true) +public class ResourceResolverTryWithResourcesCheck extends BaseTreeVisitor implements + JavaFileScanner { + + public static final String RULE_KEY = "AEM-20"; + + protected static final String RULE_MESSAGE = "ResourceResolver can be closed using try-with-resources Java 7 feature."; + + private static final String SLING_RESOURCE_RESOLVER = "org.apache.sling.api.resource.ResourceResolver"; + private final List resourceResolversInTryWithResources = new ArrayList<>(); + private boolean insideTryStatement = false; + private boolean insideLambdaExpression = false; + private JavaFileScannerContext context; + + public void scanFile(JavaFileScannerContext javaFileScannerContext) { + context = javaFileScannerContext; + scan(context.getTree()); + } + + @Override + public void visitVariable(VariableTree tree) { + if (isResourceResolverUsedProperly(tree)) { + context.reportIssue(this, tree, RULE_MESSAGE); + } + super.visitVariable(tree); + } + + @Override + public void visitAssignmentExpression(AssignmentExpressionTree tree) { + if (insideTryStatement && !insideLambdaExpression && isResourceResolver(tree)) { + context.reportIssue(this, tree, RULE_MESSAGE); + } + super.visitAssignmentExpression(tree); + } + + @Override + public void visitTryStatement(TryStatementTree tree) { + insideTryStatement = true; + tree.resourceList().stream() + // We're iterating over a resource specification in a try-with-resource block + // so we expect variable trees + .filter(VariableTree.class::isInstance) + .map(VariableTree.class::cast) + .map(resource -> resource.simpleName().name()) + .forEach(resourceResolversInTryWithResources::add); + + super.visitTryStatement(tree); + resourceResolversInTryWithResources.clear(); + insideTryStatement = false; + } + + @Override + public void visitLambdaExpression(LambdaExpressionTree lambdaExpressionTree) { + insideLambdaExpression = true; + super.visitLambdaExpression(lambdaExpressionTree); + insideLambdaExpression = false; + } + + private boolean isResourceResolverUsedProperly(VariableTree tree) { + return insideTryStatement && !insideLambdaExpression && isResourceResolver(tree) + && !resourceResolversInTryWithResources + .contains(getResourceResolver(tree)); + } + + private boolean isResourceResolver(AssignmentExpressionTree tree) { + return SLING_RESOURCE_RESOLVER.equals(tree.variable().symbolType().fullyQualifiedName()); + } + + private boolean isResourceResolver(VariableTree tree) { + return SLING_RESOURCE_RESOLVER.equals(tree.type().symbolType().fullyQualifiedName()); + } + + private String getResourceResolver(VariableTree tree) { + return tree.simpleName().name(); + } +} diff --git a/src/main/java/com/cognifide/aemrules/java/checks/slingmodels/DefaultInjectionStrategyAnnotationCheck.java b/src/main/java/com/vml/aemrules/java/checks/slingmodels/DefaultInjectionStrategyAnnotationCheck.java similarity index 86% rename from src/main/java/com/cognifide/aemrules/java/checks/slingmodels/DefaultInjectionStrategyAnnotationCheck.java rename to src/main/java/com/vml/aemrules/java/checks/slingmodels/DefaultInjectionStrategyAnnotationCheck.java index 7d92a0b4..9c3770aa 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/slingmodels/DefaultInjectionStrategyAnnotationCheck.java +++ b/src/main/java/com/vml/aemrules/java/checks/slingmodels/DefaultInjectionStrategyAnnotationCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,13 +17,9 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks.slingmodels; +package com.vml.aemrules.java.checks.slingmodels; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import java.util.List; -import org.sonar.check.Priority; +import com.vml.aemrules.version.AemVersion; import org.sonar.check.Rule; import org.sonar.plugins.java.api.JavaFileScanner; import org.sonar.plugins.java.api.JavaFileScannerContext; @@ -37,18 +33,10 @@ import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; import org.sonar.plugins.java.api.tree.Tree; -@Rule( - key = DefaultInjectionStrategyAnnotationCheck.RULE_KEY, - name = DefaultInjectionStrategyAnnotationCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = {Tags.AEM, Tags.SLING_MODELS} -) -@AemVersion( - all = true -) -@Metadata( - technicalDebt = "5min" -) +import java.util.List; + +@Rule(key = DefaultInjectionStrategyAnnotationCheck.RULE_KEY) +@AemVersion(all = true) public class DefaultInjectionStrategyAnnotationCheck extends BaseTreeVisitor implements JavaFileScanner { public static final String RULE_KEY = "AEM-16"; @@ -76,9 +64,9 @@ public void visitClass(ClassTree tree) { List annotations = tree.modifiers().annotations(); for (AnnotationTree annotationTree : annotations) { if (isSearchedAnnotation(annotationTree, MODEL_ANNOTATION_FULL_NAME) - && isOptionalDefaultValue(annotationTree.arguments())) { + && isOptionalDefaultValue(annotationTree.arguments())) { CheckIfOptionalAnnotationIsPresent checkIfOptionalIsPresent = new CheckIfOptionalAnnotationIsPresent( - this); + this); tree.accept(checkIfOptionalIsPresent); } } diff --git a/src/main/java/com/cognifide/aemrules/java/checks/slingquery/SlingQueryImplicitStrategyCheck.java b/src/main/java/com/vml/aemrules/java/checks/slingquery/SlingQueryImplicitStrategyCheck.java similarity index 91% rename from src/main/java/com/cognifide/aemrules/java/checks/slingquery/SlingQueryImplicitStrategyCheck.java rename to src/main/java/com/vml/aemrules/java/checks/slingquery/SlingQueryImplicitStrategyCheck.java index 421bc159..f2ec9f10 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/slingquery/SlingQueryImplicitStrategyCheck.java +++ b/src/main/java/com/vml/aemrules/java/checks/slingquery/SlingQueryImplicitStrategyCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,13 +17,9 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks.slingquery; +package com.vml.aemrules.java.checks.slingquery; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; -import java.util.HashMap; -import java.util.Map; -import org.sonar.check.Priority; +import com.vml.aemrules.version.AemVersion; import org.sonar.check.Rule; import org.sonar.plugins.java.api.JavaFileScanner; import org.sonar.plugins.java.api.JavaFileScannerContext; @@ -34,15 +30,11 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonar.plugins.java.api.tree.VariableTree; -@Rule( - key = SlingQueryImplicitStrategyCheck.RULE_KEY, - name = SlingQueryImplicitStrategyCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = Tags.AEM -) -@AemVersion( - all = true -) +import java.util.HashMap; +import java.util.Map; + +@Rule(key = SlingQueryImplicitStrategyCheck.RULE_KEY) +@AemVersion(all = true) public class SlingQueryImplicitStrategyCheck extends BaseTreeVisitor implements JavaFileScanner { protected static final String RULE_KEY = "AEM-19"; @@ -58,11 +50,8 @@ public class SlingQueryImplicitStrategyCheck extends BaseTreeVisitor implements private static final String SLING_QUERY = "SlingQuery"; private static final String DOLLAR_SIGN = "$"; - + private final Map slingQueries = new HashMap<>(); private String currentSlingQueryVariableName = null; - - private Map slingQueries = new HashMap<>(); - private boolean findMethodUsed = false; private boolean searchStrategyMethodUsed = false; @@ -173,4 +162,4 @@ private enum SlingQueryStates { STRATEGY_USED, ISSUE_RETURNED } -} \ No newline at end of file +} diff --git a/src/main/java/com/cognifide/aemrules/java/checks/visitors/CheckClosedVisitor.java b/src/main/java/com/vml/aemrules/java/checks/visitors/CheckClosedVisitor.java similarity index 93% rename from src/main/java/com/cognifide/aemrules/java/checks/visitors/CheckClosedVisitor.java rename to src/main/java/com/vml/aemrules/java/checks/visitors/CheckClosedVisitor.java index 10b7b784..4cda4c01 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/visitors/CheckClosedVisitor.java +++ b/src/main/java/com/vml/aemrules/java/checks/visitors/CheckClosedVisitor.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks.visitors; +package com.vml.aemrules.java.checks.visitors; import org.sonar.plugins.java.api.tree.BaseTreeVisitor; import org.sonar.plugins.java.api.tree.IdentifierTree; diff --git a/src/main/java/com/cognifide/aemrules/java/checks/visitors/CheckLoggedOutVisitor.java b/src/main/java/com/vml/aemrules/java/checks/visitors/CheckLoggedOutVisitor.java similarity index 93% rename from src/main/java/com/cognifide/aemrules/java/checks/visitors/CheckLoggedOutVisitor.java rename to src/main/java/com/vml/aemrules/java/checks/visitors/CheckLoggedOutVisitor.java index 6ae244fb..3b9b98f7 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/visitors/CheckLoggedOutVisitor.java +++ b/src/main/java/com/vml/aemrules/java/checks/visitors/CheckLoggedOutVisitor.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks.visitors; +package com.vml.aemrules.java.checks.visitors; import org.sonar.plugins.java.api.tree.BaseTreeVisitor; import org.sonar.plugins.java.api.tree.IdentifierTree; diff --git a/src/main/java/com/cognifide/aemrules/java/checks/visitors/FinallyBlockVisitor.java b/src/main/java/com/vml/aemrules/java/checks/visitors/FinallyBlockVisitor.java similarity index 91% rename from src/main/java/com/cognifide/aemrules/java/checks/visitors/FinallyBlockVisitor.java rename to src/main/java/com/vml/aemrules/java/checks/visitors/FinallyBlockVisitor.java index f9c91524..30e5d666 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/visitors/FinallyBlockVisitor.java +++ b/src/main/java/com/vml/aemrules/java/checks/visitors/FinallyBlockVisitor.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks.visitors; +package com.vml.aemrules.java.checks.visitors; import org.sonar.plugins.java.api.tree.BaseTreeVisitor; import org.sonar.plugins.java.api.tree.TreeVisitor; diff --git a/src/main/java/com/cognifide/aemrules/java/checks/visitors/FindSessionDeclarationVisitor.java b/src/main/java/com/vml/aemrules/java/checks/visitors/FindSessionDeclarationVisitor.java similarity index 96% rename from src/main/java/com/cognifide/aemrules/java/checks/visitors/FindSessionDeclarationVisitor.java rename to src/main/java/com/vml/aemrules/java/checks/visitors/FindSessionDeclarationVisitor.java index 36c0ab6c..6a01431d 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/visitors/FindSessionDeclarationVisitor.java +++ b/src/main/java/com/vml/aemrules/java/checks/visitors/FindSessionDeclarationVisitor.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks.visitors; +package com.vml.aemrules.java.checks.visitors; import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; import org.sonar.plugins.java.api.tree.BaseTreeVisitor; @@ -112,14 +112,14 @@ public void visitReturnStatement(ReturnStatementTree tree) { IdentifierTree identifier = (IdentifierTree) tree.expression(); Tree declaration = getDeclaration(identifier); if (sessions.contains(declaration)) { - sessions.remove(declaration); + sessions.remove(declaration); } } super.visitReturnStatement(tree); } private boolean isSlingRepository(MethodInvocationTree methodInvocation) { - return methodInvocation.symbol().owner().type().fullyQualifiedName().equals(SLING_REPOSITORY); + return methodInvocation.methodSymbol().owner().type().fullyQualifiedName().equals(SLING_REPOSITORY); } private boolean isSession(MethodInvocationTree methodInvocation) { @@ -188,4 +188,4 @@ public Tree getDeclarationOfReturnedVariable() { } -} \ No newline at end of file +} diff --git a/src/main/java/com/cognifide/aemrules/java/checks/visitors/FindVariableDeclarationVisitor.java b/src/main/java/com/vml/aemrules/java/checks/visitors/FindVariableDeclarationVisitor.java similarity index 94% rename from src/main/java/com/cognifide/aemrules/java/checks/visitors/FindVariableDeclarationVisitor.java rename to src/main/java/com/vml/aemrules/java/checks/visitors/FindVariableDeclarationVisitor.java index 3d76ad15..135c6fb5 100644 --- a/src/main/java/com/cognifide/aemrules/java/checks/visitors/FindVariableDeclarationVisitor.java +++ b/src/main/java/com/vml/aemrules/java/checks/visitors/FindVariableDeclarationVisitor.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,16 +17,16 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks.visitors; - -import java.util.ArrayList; -import java.util.List; +package com.vml.aemrules.java.checks.visitors; import org.sonar.plugins.java.api.tree.BaseTreeVisitor; import org.sonar.plugins.java.api.tree.MethodTree; import org.sonar.plugins.java.api.tree.TryStatementTree; import org.sonar.plugins.java.api.tree.VariableTree; +import java.util.ArrayList; +import java.util.List; + /** * Finds all injector variable declarations. Used in method's bodies only. */ diff --git a/src/main/java/com/vml/aemrules/java/rules/JavaCheckRegistrar.java b/src/main/java/com/vml/aemrules/java/rules/JavaCheckRegistrar.java new file mode 100644 index 00000000..cebd0547 --- /dev/null +++ b/src/main/java/com/vml/aemrules/java/rules/JavaCheckRegistrar.java @@ -0,0 +1,67 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.java.rules; + +import com.vml.aemrules.version.AemVersion; +import com.vml.aemrules.version.VersionSupportChecker; +import org.sonar.api.config.Configuration; +import org.sonar.plugins.java.api.CheckRegistrar; +import org.sonar.plugins.java.api.JavaCheck; +import org.sonarsource.api.sonarlint.SonarLintSide; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static com.vml.aemrules.java.Constants.REPOSITORY_KEY; + +@SonarLintSide +public class JavaCheckRegistrar implements CheckRegistrar { + + private final String aemVersion; + + public JavaCheckRegistrar(Configuration configuration) { + this.aemVersion = configuration.get(VersionSupportChecker.VERSION_PROPERTY) + .orElse(VersionSupportChecker.DEFAULT_AEM_VERSION); + } + + @Override + public void register(RegistrarContext registrarContext) { + registrarContext.registerClassesForRepository(REPOSITORY_KEY, checkClasses(), testCheckClasses()); + } + + private List> checkClasses() { + return JavaRulesList.getJavaChecks().stream() + .filter(checkClass -> shouldRegister(aemVersion, checkClass)) + .collect(Collectors.toList()); + } + + private List> testCheckClasses() { + return JavaRulesList.getJavaTestChecks().stream() + .filter(checkClass -> shouldRegister(aemVersion, checkClass)) + .collect(Collectors.toList()); + } + + private boolean shouldRegister(String aemVersion, Class checkClass) { + return Optional.ofNullable(checkClass.getAnnotation(AemVersion.class)) + .map(supportedVersion -> VersionSupportChecker.create(supportedVersion).supports(aemVersion)) + .orElse(true); + } +} diff --git a/src/main/java/com/vml/aemrules/java/rules/JavaRulesDefinition.java b/src/main/java/com/vml/aemrules/java/rules/JavaRulesDefinition.java new file mode 100644 index 00000000..5e077dbf --- /dev/null +++ b/src/main/java/com/vml/aemrules/java/rules/JavaRulesDefinition.java @@ -0,0 +1,50 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.java.rules; + +import org.sonar.api.SonarRuntime; +import org.sonar.api.server.rule.RulesDefinition; +import org.sonarsource.analyzer.commons.RuleMetadataLoader; +import org.sonarsource.api.sonarlint.SonarLintSide; + +import java.util.ArrayList; + +import static com.vml.aemrules.java.Constants.REPOSITORY_KEY; +import static com.vml.aemrules.java.Constants.REPOSITORY_NAME; + +@SonarLintSide +public class JavaRulesDefinition implements RulesDefinition { + + private static final String RESOURCE_BASE_PATH = "org/sonar/l10n/java/rules/java"; + + private final SonarRuntime runtime; + + public JavaRulesDefinition(SonarRuntime runtime) { + this.runtime = runtime; + } + + @Override + public void define(Context context) { + NewRepository repository = context.createRepository(REPOSITORY_KEY, "java").setName(REPOSITORY_NAME); + RuleMetadataLoader ruleMetadataLoader = new RuleMetadataLoader(RESOURCE_BASE_PATH, runtime); + ruleMetadataLoader.addRulesByAnnotatedClass(repository, new ArrayList<>(JavaRulesList.getChecks())); + repository.done(); + } +} diff --git a/src/main/java/com/vml/aemrules/java/rules/JavaRulesList.java b/src/main/java/com/vml/aemrules/java/rules/JavaRulesList.java new file mode 100644 index 00000000..5b24abe7 --- /dev/null +++ b/src/main/java/com/vml/aemrules/java/rules/JavaRulesList.java @@ -0,0 +1,73 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.java.rules; + +import com.vml.aemrules.java.checks.AdministrativeAccessUsageCheck; +import com.vml.aemrules.java.checks.AnnotationsConstantsCheck; +import com.vml.aemrules.java.checks.ConstantsCheck; +import com.vml.aemrules.java.checks.ContentResourceShouldBeNullCheckedCheck; +import com.vml.aemrules.java.checks.ModifiableValueMapUsageCheck; +import com.vml.aemrules.java.checks.PreferSlingServletAnnotation; +import com.vml.aemrules.java.checks.SessionShouldBeLoggedOut; +import com.vml.aemrules.java.checks.SynchronizedKeywordUsageCheck; +import com.vml.aemrules.java.checks.ThreadSafeFieldCheck; +import com.vml.aemrules.java.checks.resourceresolver.close.ResourceResolverShouldBeClosed; +import com.vml.aemrules.java.checks.resourceresolver.close.ResourceResolverTryWithResourcesCheck; +import com.vml.aemrules.java.checks.slingmodels.DefaultInjectionStrategyAnnotationCheck; +import com.vml.aemrules.java.checks.slingquery.SlingQueryImplicitStrategyCheck; +import org.sonar.plugins.java.api.JavaCheck; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class JavaRulesList { + + private JavaRulesList() { + //private constructor + } + + public static List> getChecks() { + List> checks = new ArrayList<>(); + checks.addAll(getJavaChecks()); + checks.addAll(getJavaTestChecks()); + return Collections.unmodifiableList(checks); + } + + public static List> getJavaChecks() { + return List.of(AdministrativeAccessUsageCheck.class, + AnnotationsConstantsCheck.class, ConstantsCheck.class, + PreferSlingServletAnnotation.class, + ResourceResolverShouldBeClosed.class, + SessionShouldBeLoggedOut.class, + SynchronizedKeywordUsageCheck.class, + ThreadSafeFieldCheck.class, + DefaultInjectionStrategyAnnotationCheck.class, + ModifiableValueMapUsageCheck.class, + ContentResourceShouldBeNullCheckedCheck.class, + SlingQueryImplicitStrategyCheck.class, + ResourceResolverTryWithResourcesCheck.class); + } + + public static List> getJavaTestChecks() { + return Collections.emptyList(); + } + +} diff --git a/src/main/java/com/cognifide/aemrules/java/util/ConstantsChecker.java b/src/main/java/com/vml/aemrules/java/util/ConstantsChecker.java similarity index 99% rename from src/main/java/com/cognifide/aemrules/java/util/ConstantsChecker.java rename to src/main/java/com/vml/aemrules/java/util/ConstantsChecker.java index e78c0dbd..4dc6276a 100644 --- a/src/main/java/com/cognifide/aemrules/java/util/ConstantsChecker.java +++ b/src/main/java/com/vml/aemrules/java/util/ConstantsChecker.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.util; +package com.vml.aemrules.java.util; import java.util.AbstractMap; import java.util.Map; diff --git a/src/main/java/com/cognifide/aemrules/java/util/TypeUtils.java b/src/main/java/com/vml/aemrules/java/util/TypeUtils.java similarity index 90% rename from src/main/java/com/cognifide/aemrules/java/util/TypeUtils.java rename to src/main/java/com/vml/aemrules/java/util/TypeUtils.java index 39743598..bc8dfdd3 100644 --- a/src/main/java/com/cognifide/aemrules/java/util/TypeUtils.java +++ b/src/main/java/com/vml/aemrules/java/util/TypeUtils.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.util; +package com.vml.aemrules.java.util; import org.sonar.plugins.java.api.tree.TypeTree; diff --git a/src/main/java/com/cognifide/aemrules/matcher/MethodMatcher.java b/src/main/java/com/vml/aemrules/matcher/MethodMatcher.java similarity index 86% rename from src/main/java/com/cognifide/aemrules/matcher/MethodMatcher.java rename to src/main/java/com/vml/aemrules/matcher/MethodMatcher.java index 4f1d75a7..cdd661bd 100644 --- a/src/main/java/com/cognifide/aemrules/matcher/MethodMatcher.java +++ b/src/main/java/com/vml/aemrules/matcher/MethodMatcher.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,8 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.matcher; +package com.vml.aemrules.matcher; -import java.util.Arrays; -import java.util.List; import org.sonar.plugins.java.api.semantic.Symbol; import org.sonar.plugins.java.api.semantic.Symbol.MethodSymbol; import org.sonar.plugins.java.api.tree.IdentifierTree; @@ -28,23 +26,26 @@ import org.sonar.plugins.java.api.tree.MethodInvocationTree; import org.sonar.plugins.java.api.tree.Tree; +import java.util.Arrays; +import java.util.List; + public final class MethodMatcher { - private OwnerTypePredicate methodOwnerTypePredicate; + private final OwnerTypePredicate methodOwnerTypePredicate; - private MethodNamePredicate methodNamePredicate; + private final MethodNamePredicate methodNamePredicate; - private MethodParametersPredicate methodParametersPredicate; + private final MethodParametersPredicate methodParametersPredicate; private MethodMatcher(MethodNamePredicate methodNamePredicate, OwnerTypePredicate methodOwnerTypePredicate, - List methodParameterTypePredicates) { + List methodParameterTypePredicates) { this.methodNamePredicate = methodNamePredicate; this.methodOwnerTypePredicate = methodOwnerTypePredicate; this.methodParametersPredicate = MethodParametersPredicate.of(methodParameterTypePredicates); } public static MethodMatcher create(MethodNamePredicate methodNamePredicate, OwnerTypePredicate methodOwnerTypePredicate, - ParameterTypePredicate... methodParameterTypePredicates) { + ParameterTypePredicate... methodParameterTypePredicates) { return new MethodMatcher(methodNamePredicate, methodOwnerTypePredicate, Arrays.asList(methodParameterTypePredicates)); } diff --git a/src/main/java/com/cognifide/aemrules/matcher/MethodNamePredicate.java b/src/main/java/com/vml/aemrules/matcher/MethodNamePredicate.java similarity index 90% rename from src/main/java/com/cognifide/aemrules/matcher/MethodNamePredicate.java rename to src/main/java/com/vml/aemrules/matcher/MethodNamePredicate.java index f27398d1..43c0478a 100644 --- a/src/main/java/com/cognifide/aemrules/matcher/MethodNamePredicate.java +++ b/src/main/java/com/vml/aemrules/matcher/MethodNamePredicate.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.matcher; +package com.vml.aemrules.matcher; import java.util.function.Predicate; diff --git a/src/main/java/com/cognifide/aemrules/matcher/MethodParametersPredicate.java b/src/main/java/com/vml/aemrules/matcher/MethodParametersPredicate.java similarity index 94% rename from src/main/java/com/cognifide/aemrules/matcher/MethodParametersPredicate.java rename to src/main/java/com/vml/aemrules/matcher/MethodParametersPredicate.java index 1f74c35a..6a761256 100644 --- a/src/main/java/com/cognifide/aemrules/matcher/MethodParametersPredicate.java +++ b/src/main/java/com/vml/aemrules/matcher/MethodParametersPredicate.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,12 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.matcher; +package com.vml.aemrules.matcher; + +import org.sonar.plugins.java.api.semantic.Type; import java.util.List; import java.util.function.Predicate; -import org.sonar.plugins.java.api.semantic.Type; @FunctionalInterface public interface MethodParametersPredicate extends Predicate> { diff --git a/src/main/java/com/cognifide/aemrules/matcher/OwnerTypePredicate.java b/src/main/java/com/vml/aemrules/matcher/OwnerTypePredicate.java similarity index 90% rename from src/main/java/com/cognifide/aemrules/matcher/OwnerTypePredicate.java rename to src/main/java/com/vml/aemrules/matcher/OwnerTypePredicate.java index b8316b34..f1b1a6c4 100644 --- a/src/main/java/com/cognifide/aemrules/matcher/OwnerTypePredicate.java +++ b/src/main/java/com/vml/aemrules/matcher/OwnerTypePredicate.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,12 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.matcher; +package com.vml.aemrules.matcher; -import java.util.function.Predicate; import org.sonar.plugins.java.api.semantic.Type; +import java.util.function.Predicate; + @FunctionalInterface public interface OwnerTypePredicate extends Predicate { diff --git a/src/main/java/com/cognifide/aemrules/matcher/ParameterTypePredicate.java b/src/main/java/com/vml/aemrules/matcher/ParameterTypePredicate.java similarity index 91% rename from src/main/java/com/cognifide/aemrules/matcher/ParameterTypePredicate.java rename to src/main/java/com/vml/aemrules/matcher/ParameterTypePredicate.java index 56b5b350..b7f2f0c8 100644 --- a/src/main/java/com/cognifide/aemrules/matcher/ParameterTypePredicate.java +++ b/src/main/java/com/vml/aemrules/matcher/ParameterTypePredicate.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,12 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.matcher; +package com.vml.aemrules.matcher; -import java.util.function.Predicate; import org.sonar.plugins.java.api.semantic.Type; +import java.util.function.Predicate; + @FunctionalInterface public interface ParameterTypePredicate extends Predicate { diff --git a/src/main/java/com/cognifide/aemrules/utils/Comparables.java b/src/main/java/com/vml/aemrules/utils/Comparables.java similarity index 92% rename from src/main/java/com/cognifide/aemrules/utils/Comparables.java rename to src/main/java/com/vml/aemrules/utils/Comparables.java index 70792deb..7b29fbdb 100644 --- a/src/main/java/com/cognifide/aemrules/utils/Comparables.java +++ b/src/main/java/com/vml/aemrules/utils/Comparables.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.utils; +package com.vml.aemrules.utils; import java.util.Iterator; diff --git a/src/main/java/com/cognifide/aemrules/utils/Throwables.java b/src/main/java/com/vml/aemrules/utils/Throwables.java similarity index 77% rename from src/main/java/com/cognifide/aemrules/utils/Throwables.java rename to src/main/java/com/vml/aemrules/utils/Throwables.java index 9f15220b..0589a15d 100644 --- a/src/main/java/com/cognifide/aemrules/utils/Throwables.java +++ b/src/main/java/com/vml/aemrules/utils/Throwables.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.utils; +package com.vml.aemrules.utils; public final class Throwables { @@ -27,7 +27,7 @@ private Throwables() { public static Throwable getRootCause(Throwable throwable) { Throwable cause; - while((cause = throwable.getCause()) != null) { + while ((cause = throwable.getCause()) != null) { throwable = cause; } @@ -36,7 +36,7 @@ public static Throwable getRootCause(Throwable throwable) { public static RuntimeException propagate(Throwable throwable) { throwIfUnchecked(throwable); - throw new RuntimeException(throwable); + throw new AemRulesTestRuntimeException(throwable); } public static void throwIfUnchecked(Throwable throwable) { @@ -47,4 +47,10 @@ public static void throwIfUnchecked(Throwable throwable) { throw (Error) throwable; } } + + private static class AemRulesTestRuntimeException extends RuntimeException { + public AemRulesTestRuntimeException(Throwable throwable) { + super(throwable); + } + } } diff --git a/src/main/java/com/cognifide/aemrules/version/AemVersion.java b/src/main/java/com/vml/aemrules/version/AemVersion.java similarity index 93% rename from src/main/java/com/cognifide/aemrules/version/AemVersion.java rename to src/main/java/com/vml/aemrules/version/AemVersion.java index f755bbae..683bfb65 100644 --- a/src/main/java/com/cognifide/aemrules/version/AemVersion.java +++ b/src/main/java/com/vml/aemrules/version/AemVersion.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.version; +package com.vml.aemrules.version; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/java/com/cognifide/aemrules/version/Version.java b/src/main/java/com/vml/aemrules/version/Version.java similarity index 85% rename from src/main/java/com/cognifide/aemrules/version/Version.java rename to src/main/java/com/vml/aemrules/version/Version.java index 4737bf4c..2408296f 100644 --- a/src/main/java/com/cognifide/aemrules/version/Version.java +++ b/src/main/java/com/vml/aemrules/version/Version.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,16 +17,17 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.version; +package com.vml.aemrules.version; + +import org.apache.commons.lang3.StringUtils; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.commons.lang3.StringUtils; public class Version { - private static final Pattern VERSION_PATTERN = Pattern.compile("(?[0-9]+)\\.(?[0-9])"); + private static final Pattern VERSION_PATTERN = Pattern.compile("(?\\d+)\\.(?\\d)"); private final int major; @@ -45,7 +46,7 @@ public static Version of(String version) { Matcher versionMatcher = VERSION_PATTERN.matcher(version); if (!versionMatcher.matches()) { throw new IllegalArgumentException( - "Incorrect AEM version format provided: " + version + " expected pattern: [0-9]+.[0-9]"); + "Incorrect AEM version format provided: " + version + " expected pattern: [0-9]+.[0-9]"); } int major = Integer.parseInt(versionMatcher.group("major")); int minor = Integer.parseInt(versionMatcher.group("minor")); @@ -55,7 +56,7 @@ public static Version of(String version) { public boolean isEqualOrGreaterThan(Version version) { return version.major < this.major - || (version.major == this.major && version.minor <= this.minor); + || (version.major == this.major && version.minor <= this.minor); } @Override @@ -68,7 +69,7 @@ public boolean equals(Object o) { } Version version = (Version) o; return major == version.major && - minor == version.minor; + minor == version.minor; } @Override diff --git a/src/main/java/com/cognifide/aemrules/version/VersionSupportChecker.java b/src/main/java/com/vml/aemrules/version/VersionSupportChecker.java similarity index 87% rename from src/main/java/com/cognifide/aemrules/version/VersionSupportChecker.java rename to src/main/java/com/vml/aemrules/version/VersionSupportChecker.java index 43aaf513..8a28f939 100644 --- a/src/main/java/com/cognifide/aemrules/version/VersionSupportChecker.java +++ b/src/main/java/com/vml/aemrules/version/VersionSupportChecker.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,18 +17,19 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.version; +package com.vml.aemrules.version; + +import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; -import org.apache.commons.lang3.StringUtils; public class VersionSupportChecker { public static final String VERSION_PROPERTY = "sonarRunner.aemVersion"; - public static final String DEFAULT_AEM_VERSION = "6.4"; + public static final String DEFAULT_AEM_VERSION = "6.5"; private boolean all = false; @@ -72,14 +73,14 @@ private void to(String version) { private void included(String[] versions) { this.included = Arrays.stream(versions) - .map(Version::of) - .collect(Collectors.toSet()); + .map(Version::of) + .collect(Collectors.toSet()); } private void excluded(String[] versions) { this.excluded = Arrays.stream(versions) - .map(Version::of) - .collect(Collectors.toSet()); + .map(Version::of) + .collect(Collectors.toSet()); } private void all(boolean all) { @@ -97,10 +98,10 @@ private boolean isExcluded(Version aemVersion) { private boolean supportsVersion(Version aemVersion) { return all || - included.contains(aemVersion) || - isBetween(aemVersion) || - isFrom(aemVersion) || - isTo(aemVersion); + included.contains(aemVersion) || + isBetween(aemVersion) || + isFrom(aemVersion) || + isTo(aemVersion); } private boolean isBetween(Version version) { diff --git a/src/main/resources/com/vml/rules/htl/HTL-0.html b/src/main/resources/com/vml/rules/htl/HTL-0.html new file mode 100644 index 00000000..86270e31 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-0.html @@ -0,0 +1 @@ +

Compilation error

\ No newline at end of file diff --git a/src/main/resources/com/vml/rules/htl/HTL-0.json b/src/main/resources/com/vml/rules/htl/HTL-0.json new file mode 100644 index 00000000..19eb8c25 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-0.json @@ -0,0 +1,14 @@ +{ + "title": "Compilation error", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "HTL-0" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-1.html b/src/main/resources/com/vml/rules/htl/HTL-1.html new file mode 100644 index 00000000..b9e7f714 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-1.html @@ -0,0 +1,10 @@ +

Always Place HTL Attributes After the Ones that are Part of the Markup

+

It's easier to understand HTL code if the attributes processed server-side are visually separated from the ones used at the front-end.

+

Noncompliant Code Example

+
+<div data-sly-test="${model.enabled}" class="decorated" data-sly-unwrap="${!model.decorated}"> // Bad - mixing HTL attributes with other ones
+
+

Compliant Solution

+
+<div class="decorated" data-sly-test="${model.enabled}" data-sly-unwrap="${!model.decorated}"> // Good - HTL-specific attributes grouped at the end of the element
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-1.json b/src/main/resources/com/vml/rules/htl/HTL-1.json new file mode 100644 index 00000000..370f44b1 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-1.json @@ -0,0 +1,14 @@ +{ + "title": "Always place HTL attributes at the end", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "HTL-1" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-10.html b/src/main/resources/com/vml/rules/htl/HTL-10.html new file mode 100644 index 00000000..f863ea2b --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-10.html @@ -0,0 +1,10 @@ +

If it's not possible to use an existing element, prefer sly tags over introducing superfluous markup that renders on the page.

+

Noncompliant Code Example

+
+<div data-sly-use.model="com.example.Model" data-sly-use.templates="templates.html"></div>
+<div data-sly-use.model="com.example.Model" data-sly-use.templates="templates.html" data-sly-unwrap></div>
+
+

Compliant Solution

+
+<sly data-sly-use.model="com.example.Model" data-sly-use.templates="templates.html"></sly>
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-10.json b/src/main/resources/com/vml/rules/htl/HTL-10.json new file mode 100644 index 00000000..c9c31c99 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-10.json @@ -0,0 +1,14 @@ +{ + "title": "Use sly tags over redundant markup", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "HTL-10" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-11.html b/src/main/resources/com/vml/rules/htl/HTL-11.html new file mode 100644 index 00000000..e68bce60 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-11.html @@ -0,0 +1,19 @@ +

Use existing HTML elements instead of adding extra sly tags.

+

Noncompliant Code Example

+
+<sly data-sly-test="${model.visible}" data-sly-use="com.example.HeroModel">
+    <div class="myComponent">
+        <h1>${model.headline}</h1>
+        <p>${model.text}</p>
+    </div>
+</sly>
+
+

Compliant Solution

+
+<div class="myComponent"
+     data-sly-test="${model.visible}"
+     data-sly-use="com.example.HeroModel">
+    <h1>${model.headline}</h1>
+    <p>${model.text}</p>
+</div>
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-11.json b/src/main/resources/com/vml/rules/htl/HTL-11.json new file mode 100644 index 00000000..d6d17818 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-11.json @@ -0,0 +1,14 @@ +{ + "title": "Use existing HTML elements instead of adding extra sly tags", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "HTL-11" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-12.html b/src/main/resources/com/vml/rules/htl/HTL-12.html new file mode 100644 index 00000000..979b3db1 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-12.html @@ -0,0 +1,30 @@ +

Use the most restrictive HTL context possible.

+

Noncompliant Code Example

+
+<div data-index-number="${model.index}"></div>
+
+

Compliant Solution

+
+<div data-index-number="${model.index @ context='number'}"></div>
+
+

Available markup context:

+
    +
  • html - Use this in case you want to output HTMLRemoves markup that may contain XSS risks
  • +
  • text - Use this for simple HTML contentEncodes all HTML
  • +
  • elementName - Allows only element names that are white-listed, outputs 'div' otherwise -
  • +
  • attributeName - Outputs nothing if the value doesn't correspond to the HTML attribute name syntaxdoesn't allow 'style' and 'on*' attributes
  • +
  • attribute - Applies HTML attribute escaping
  • +
  • uri - Outputs nothing if the value contains XSS risks
  • +
  • scriptToken - Outputs nothing if the value doesn't correspond to an Identifier, String literal or Numeric literal JavaScript token
  • +
  • scriptString - Applies JavaScript string escaping
  • +
  • scriptComment - Context for Javascript block comments. Outputs nothing if value is trying to break out of the comment context
  • +
  • scriptRegExp - Applies JavaScript regular expression escaping
  • +
  • styleToken - Outputs nothing if the value doesn't correspond to the CSS token syntax
  • +
  • styleString - Applies CSS string escaping
  • +
  • styleComment - Context for CSS comments. Outputs nothing if value is trying to break out of the comment context
  • +
  • comment - Applies HTML comment escaping
  • +
  • number - Outputs zero if the value is not a number
  • +
  • unsafe - Use this at your own risk, this disables XSS protection completely
  • +
+

See

+Source diff --git a/src/main/resources/com/vml/rules/htl/HTL-12.json b/src/main/resources/com/vml/rules/htl/HTL-12.json new file mode 100644 index 00000000..1b3eebbf --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-12.json @@ -0,0 +1,14 @@ +{ + "title": "Use the most restrictive HTL context possible", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "HTL-12" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-13.html b/src/main/resources/com/vml/rules/htl/HTL-13.html new file mode 100644 index 00000000..bae826ef --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-13.html @@ -0,0 +1,13 @@ +

Avoid using 'unsafe' display context, it disables XSS protection completely.

+

Noncompliant Code Example

+
+<div class="my-component>
+    <p>${model.text @ context='unsafe'}</p>
+</div>
+
+

Compliant Solution

+
+<div class="my-component>
+    <p>${model.text}</p>
+</div>
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-13.json b/src/main/resources/com/vml/rules/htl/HTL-13.json new file mode 100644 index 00000000..d38381b1 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-13.json @@ -0,0 +1,14 @@ +{ + "title": "Avoid using 'unsafe' display context, this disables XSS protection completely", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Critical", + "sqKey": "HTL-13" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-14.html b/src/main/resources/com/vml/rules/htl/HTL-14.html new file mode 100644 index 00000000..bbdab176 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-14.html @@ -0,0 +1,9 @@ +

HTL expressions in HTML comments should have defined context.

+

Noncompliant Code Example

+
+<!--[if IE]><link rel="shortcut icon" href="${site.root}/images/favicon/favicon.ico?v2"><![endif]-->
+
+

Compliant Solution

+
+<!--[if IE]><link rel="shortcut icon" href="${site.root @ context='uri'}/images/favicon/favicon.ico?v2"><![endif]-->
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-14.json b/src/main/resources/com/vml/rules/htl/HTL-14.json new file mode 100644 index 00000000..a153f495 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-14.json @@ -0,0 +1,14 @@ +{ + "title": "Please define markup context for HTML conditional comments otherwise automatically implied context will be 'comment'", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "HTL-14" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-15.html b/src/main/resources/com/vml/rules/htl/HTL-15.html new file mode 100644 index 00000000..40b91fa2 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-15.html @@ -0,0 +1,15 @@ +

Use Camel Case in identifiers:

+
    +
  • variable names
  • +
  • template names
  • +
+

Noncompliant Code Example

+
+<sly data-sly-template.COMPONENT_VALIDATION>
+<sly data-sly-use.GalleryModel="com.example.GalleryModel">
+
+

Compliant Solution

+
+<sly data-sly-template.componentValidation>
+<sly data-sly-use.galleryModel="com.example.GalleryModel">
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-15.json b/src/main/resources/com/vml/rules/htl/HTL-15.json new file mode 100644 index 00000000..93b27549 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-15.json @@ -0,0 +1,14 @@ +{ + "title": "Use Camel Case in identifiers", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "HTL-15" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-16.html b/src/main/resources/com/vml/rules/htl/HTL-16.html new file mode 100644 index 00000000..497dd095 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-16.html @@ -0,0 +1,15 @@ +

HTL <sly> elements are automatically unwrapped.

+
    +
  • variable names
  • +
  • template names
  • +
+

Noncompliant Code Example

+
+<sly data-sly-test="${myTest}" data-sly-unwrap>Caption</sly>
+
+

Compliant Solution

+
+<sly data-sly-test="${myTest}">Caption</sly>
+
+<sly data-sly-test="${myTest}" data-sly-unwrap="${false}">Caption</sly>
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-16.json b/src/main/resources/com/vml/rules/htl/HTL-16.json new file mode 100644 index 00000000..1790987e --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-16.json @@ -0,0 +1,14 @@ +{ + "title": "HTL elements are automatically unwrapped", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "HTL-16" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-2.html b/src/main/resources/com/vml/rules/htl/HTL-2.html new file mode 100644 index 00000000..f56a5696 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-2.html @@ -0,0 +1,14 @@ +

+ HTL Templates should be placed in separate files. This helps to understand which code is meant to render a component and which code is re-used as a template. + Additionally, component-specific code can be safely removed. It should be immediately obvious whether or not some code is re-used across the codebase. +

+

Noncompliant Code Example

+
+<template data-sly-template.image="${@ source, description}">
+    <img src="${source}" alt="${description}" title="${description}"/>
+</template>
+
+<div class="image-component" data-sly-use.model="com.example.Image">
+    <sly data-sly-call="${image @ source=model.src, description=model.altText}"
+</div>
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-2.json b/src/main/resources/com/vml/rules/htl/HTL-2.json new file mode 100644 index 00000000..f38f05cb --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-2.json @@ -0,0 +1,14 @@ +{ + "title": "HTL Templates should be placed in separate files", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "15min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "HTL-2" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-3.html b/src/main/resources/com/vml/rules/htl/HTL-3.html new file mode 100644 index 00000000..0bbf6505 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-3.html @@ -0,0 +1,18 @@ +

HTL provides implicit variables in data-sly-list and data-sly-repeat blocks.

+

Try to avoid them and use explicit names clarifying the role of the objects instead.

+

Noncompliant Code Example

+
+<ul data-sly-list="${model.downloadableFiles}">
+    <li>
+        <a href="${item.url}">${item.name}</a>
+    </li>
+</ul>
+
+

Compliant Solution

+
+<ul data-sly-list.file="${model.downloadableFiles}">
+    <li>
+        <a href="${file.url}">${file.name}</a>
+    </li>
+</ul>
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-3.json b/src/main/resources/com/vml/rules/htl/HTL-3.json new file mode 100644 index 00000000..9e746d33 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-3.json @@ -0,0 +1,14 @@ +{ + "title": "Explicit names in loops", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "10min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "HTL-3" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-4.html b/src/main/resources/com/vml/rules/htl/HTL-4.html new file mode 100644 index 00000000..4e5144e7 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-4.html @@ -0,0 +1,19 @@ +

Always try to re-use existing conditions, so the code is more readable.

+

Noncompliant Code Example

+
+<span class="uber-mode__top-bar" data-sly-test="${uberModeHelper.uberModeEnabled || forceUberMode}">
+    <div class="my-component">
+        Some text
+    </div>
+</span>
+<span class="uber-mode__bottom-bar" data-sly-test="${uberModeHelper.uberModeEnabled || forceUberMode}"></span>
+
+

Compliant Solution

+
+<span class="uber-mode__top-bar" data-sly-test.uberMode="${uberModeHelper.uberModeEnabled || forceUberMode}">
+    <div class="my-component">
+        Some text
+    </div>
+</span>
+<span class="uber-mode__bottom-bar" data-sly-test="${uberMode}"></span>
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-4.json b/src/main/resources/com/vml/rules/htl/HTL-4.json new file mode 100644 index 00000000..99cbb90d --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-4.json @@ -0,0 +1,14 @@ +{ + "title": "Consider caching data-sly-test conditions", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "10min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Info", + "sqKey": "HTL-4" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-5.html b/src/main/resources/com/vml/rules/htl/HTL-5.html new file mode 100644 index 00000000..dd5c1b53 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-5.html @@ -0,0 +1,9 @@ +

Always use HTL style of commenting

+

Noncompliant Code Example

+
+    <!-- Potentially bad, plain HTML comments will be visible on the page -->
+
+

Compliant Solution

+
+    <!--/* Good, this comment will not be rendered */-->
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-5.json b/src/main/resources/com/vml/rules/htl/HTL-5.json new file mode 100644 index 00000000..1e127cf0 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-5.json @@ -0,0 +1,14 @@ +{ + "title": "Always use HTL style of comments", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "10min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "HTL-5" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-6.html b/src/main/resources/com/vml/rules/htl/HTL-6.html new file mode 100644 index 00000000..3cb207d3 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-6.html @@ -0,0 +1,13 @@ +

HTL uses uri display context as default for src, poster, manifest, href, formaction, data, cite, action attributes. Explicit display context definition should be removed.

+

Noncompliant Code Example

+
+<img alt="${model.imageAlt @ context='attribute'}" src="${model.imageUrl @ context='uri'}" />
+
+

Compliant Solution

+
+<img alt="${model.imageAlt}" src="${model.imageUrl}" />
+
+<div data-service-url="${model.url @ context='uri'}">
+    ${'http://www.example.org/search?s=1&q=htl' @ context='uri'}
+</div>
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-6.json b/src/main/resources/com/vml/rules/htl/HTL-6.json new file mode 100644 index 00000000..011d3ce8 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-6.json @@ -0,0 +1,14 @@ +{ + "title": "HTL uses uri display context as default for src, poster, manifest, href, formaction, data, cite, action attributes", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "HTL-6" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-7.html b/src/main/resources/com/vml/rules/htl/HTL-7.html new file mode 100644 index 00000000..99feefe3 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-7.html @@ -0,0 +1,25 @@ +

For style and script tags display context definition is mandatory.

+

Noncompliant Code Example

+
+<script>
+    var bar='${someText}';
+</script>
+
+<style>
+    a {
+        font-family: '${fontFamily}', sans-serif;
+    }
+</style>
+
+

Compliant Solution

+
+<script>
+    var bar='${someText @ context="scriptString"}';
+</script>
+
+<style>
+    a {
+        font-family: '${fontFamily @ context="styleToken"}', sans-serif;
+    }
+</style>
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-7.json b/src/main/resources/com/vml/rules/htl/HTL-7.json new file mode 100644 index 00000000..b4390236 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-7.json @@ -0,0 +1,14 @@ +{ + "title": "For style and script tags display context definition is mandatory", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Major", + "sqKey": "HTL-7" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-8.html b/src/main/resources/com/vml/rules/htl/HTL-8.html new file mode 100644 index 00000000..086aca83 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-8.html @@ -0,0 +1,9 @@ +

In HTL event attributes must contain display context definition.

+

Noncompliant Code Example

+
+<a href="#id" onclick="${myFunctionName}()">Link</a> <!--/* Non-Compliant */-->
+
+

Compliant Solution

+
+<a href="#id" onclick="${myFunctionName @ context='scriptToken'}()">Link</a>
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-8.json b/src/main/resources/com/vml/rules/htl/HTL-8.json new file mode 100644 index 00000000..7e854097 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-8.json @@ -0,0 +1,14 @@ +{ + "title": "For event attributes display context is mandatory", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Major", + "sqKey": "HTL-8" +} diff --git a/src/main/resources/com/vml/rules/htl/HTL-9.html b/src/main/resources/com/vml/rules/htl/HTL-9.html new file mode 100644 index 00000000..8f295bce --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-9.html @@ -0,0 +1,9 @@ +

For inline styles display context is mandatory.

+

Noncompliant Code Example

+
+<a href="#id" style="color: ${colorName};">Link</a>
+
+

Compliant Solution

+
+<a href="#id" style="color: ${colorName @ context='styleToken'};">Link</a>
+
diff --git a/src/main/resources/com/vml/rules/htl/HTL-9.json b/src/main/resources/com/vml/rules/htl/HTL-9.json new file mode 100644 index 00000000..77467a69 --- /dev/null +++ b/src/main/resources/com/vml/rules/htl/HTL-9.json @@ -0,0 +1,14 @@ +{ + "title": "For inline styles display context is mandatory", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Major", + "sqKey": "HTL-9" +} diff --git a/src/main/resources/metadata/AEM-19.json b/src/main/resources/metadata/AEM-19.json deleted file mode 100644 index 2027a78a..00000000 --- a/src/main/resources/metadata/AEM-19.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "remediation": { - "constantCost": "30min" - } -} diff --git a/src/main/resources/rules/AEM-1.md b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-1.html similarity index 69% rename from src/main/resources/rules/AEM-1.md rename to src/main/resources/org/sonar/l10n/java/rules/java/AEM-1.html index f32de86d..a60e46bc 100644 --- a/src/main/resources/rules/AEM-1.md +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-1.html @@ -1,13 +1,13 @@ -Use constants available in AEM instead of repeating inline literals. -== Noncompliant Code Example -`` +

Use predefined constant in annotation instead of hardcoded value.

+

Noncompliant Code Example

+
 public static final String JCR_CONTENT = "jcr:content"; // Noncompliant; Use predefined constant available in com.day.cq.commons.jcr.JcrConstants
 // ...
 Resource resource = resourceResolver.getResource(resourcePath + JCR_CONTENT);
-``
-== Compliant Solution
-``
+
+

Compliant Solution

+
 import com.day.cq.commons.jcr.JcrConstants
 // ...
 Resource resource = resourceResolver.getResource(resourcePath + JcrConstants.JCR_CONTENT);
-``
+
diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-1.json b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-1.json new file mode 100644 index 00000000..09fe6aea --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-1.json @@ -0,0 +1,14 @@ +{ + "title": "Use predefined constant in annotation instead of hardcoded value.", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "AEM-1" +} diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-11.html b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-11.html new file mode 100644 index 00000000..ac666cfe --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-11.html @@ -0,0 +1,36 @@ +

+ Administrative access to the resource tree and JCR Repository by means of usage of ResourceResolverFactory.getAdministrativeResourceResolver + and SlingRepository.loginAdministrative has been deprecated. + Use ResourceResolverFactory.getServiceResourceResolver or SlingRepository.loginService + respectively. +

+ +

Noncompliant Code Example

+
+ResourceResolver resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(credentials);
+
+
+
+Session session = slingRepository.loginAdministrative(workspace);
+
+

Compliant Solution

+
+try (ResourceResolver resourceResolver = resolverFactory.getServiceResourceResolver(null)) {
+	...
+}
+
+

or

+
+Map<String, Object> param = new HashMap<String, Object>();
+param.put(ResourceResolverFactory.SUBSERVICE, "sub service name");
+try (ResourceResolver resourceResolver = resolverFactory.getServiceResourceResolver(param)) {
+	...
+}
+
+

or

+
+Session session = slingRepository.loginService(subServiceName, workspace);
+
+

See

+ResourceResolverFactory Javadoc
+Service Authentication diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-11.json b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-11.json new file mode 100644 index 00000000..57a721cf --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-11.json @@ -0,0 +1,14 @@ +{ + "title": "Do not use deprecated administrative access methods", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "30min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Major", + "sqKey": "AEM-11" +} diff --git a/src/main/resources/rules/AEM-15.md b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-15.html similarity index 53% rename from src/main/resources/rules/AEM-15.md rename to src/main/resources/org/sonar/l10n/java/rules/java/AEM-15.html index 80c73940..3a70237d 100644 --- a/src/main/resources/rules/AEM-15.md +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-15.html @@ -1,67 +1,67 @@ -Usage of ``synchronized`` keyword should be avoided if possible. Check if using ``synchronized`` can be replaced with more sophisticated solution. +

+ Usage of synchronized keyword should be avoided if possible. Check if using synchronized + can be replaced with more sophisticated solution. +

-== Noncompliant Code Example - -`` +

Noncompliant Code Example

+
 import java.util.ArrayList;
 import java.util.List;
 (...)
-private final List list = new ArrayList<>(16);
+private final List<String> list = new ArrayList<>(16);
 
 public synchronized void addElement(String s) { // Noncompliant
 	list.add(s);
 }
-``
-or
-``
+
+

or

+
 import java.util.ArrayList;
 import java.util.List;
 (...)
-private final List list = new ArrayList<>(16);
+private final List<String> list = new ArrayList<>(16);
 
 public void removeElement(String s) {
 	synchronized(list) { // Noncompliant
 		list.remove(s);
 	}
 }
-``
-or
-``
+
+

or

+
 private int counter = 0;
 
 public synchronized void increment() { // Noncompliant
 	counter++;
 }
-``
-
-== Compliant Solution
-
-``
+
+

Compliant Solution

+
 import java.util.List;
 import java.util.concurrent.CopyOnWriteArrayList;
 (...)
-private final List list = new CopyOnWriteArrayList<>(16);
+private final ListList<String> list = new CopyOnWriteArrayList<>(16);
 // use java.util.concurrent.ConcurrentHashMap for Map
 
 public void addElement(String s) {
 	list.add(s);
 }
-``
-or
-``
+
+

or

+
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Collections;
 (...)
-private final List list = Collections.synchronizedList(new ArrayList<>(16));
+private final List<String> list = Collections.synchronizedList(new ArrayList<>(16));
 // Collections object contains also synchronizedMap function
 
 public void addElement(String s) {
 	list.add(s);
 }
-``
-or
-``
+
+

or

+
 import java.util.concurrent.atomic.AtomicInteger
 java.util.concurrent.atomic.LongAdder // from java 8
 (...)
@@ -72,9 +72,8 @@
 	counter.addAndGet(1);
 	meter.increment();
 }
-``
-
-== See
-More details:
-[Java 7 java.util.concurrent javadoc](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html)
-[Java 8 java.util.concurrent javadoc](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html)
\ No newline at end of file
+
+

See

+Java 7 java.util.concurrent javadoc +
+Java 8 java.util.concurrent javadoc diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-15.json b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-15.json new file mode 100644 index 00000000..71fc3357 --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-15.json @@ -0,0 +1,15 @@ +{ + "title": "Check if using 'synchronized' can be replaced with more sophisticated solution.", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "30min" + }, + "tags": [ + "multi-threading", + "performance" + ], + "defaultSeverity": "Info", + "sqKey": "AEM-15" +} diff --git a/src/main/resources/rules/AEM-16.md b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-16.html similarity index 62% rename from src/main/resources/rules/AEM-16.md rename to src/main/resources/org/sonar/l10n/java/rules/java/AEM-16.html index e229a8b7..a202baa8 100644 --- a/src/main/resources/rules/AEM-16.md +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-16.html @@ -1,8 +1,9 @@ -Usage of ``@Optional`` is redundant, ``defaultInjectionStrategy`` is defined as ``OPTIONAL`` +

+ Usage of @Optional is redundant, defaultInjectionStrategy is defined as OPTIONAL +

-== Noncompliant Code Example - -`` +

Noncompliant Code Example

+
 @Model(adaptables = Resource.class , defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
 public class SampleModel {
 
@@ -10,14 +11,13 @@
 @Optional //Noncompliant
 private String str1;
 (...)
-``
-== Compliant Solution
-
-``
+
+

Compliant Solution

+
 @Model(adaptables = Resource.class , defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
 public class SampleModel {
 
 @Inject // Compliant
 private String str1;
 (...)
-``
+
diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-16.json b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-16.json new file mode 100644 index 00000000..afc53f77 --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-16.json @@ -0,0 +1,15 @@ +{ + "title": "Check if using 'synchronized' can be replaced with more sophisticated solution.", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem", + "sling-models" + ], + "defaultSeverity": "Minor", + "sqKey": "AEM-16" +} diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-17.html b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-17.html new file mode 100644 index 00000000..fc49a908 --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-17.html @@ -0,0 +1,29 @@ +

+ The ModifiableValueMap + is an extension of the ValueMap which allows to modify and persist properties. + It is checking user permissions and returns `null` if the user has no permission to write. +

+ The modifiable value map is only changeable through any of the following methods: +

    +
  • put(String, Object)
  • +
  • putAll(java.util.Map)
  • +
  • remove(Object)
  • +
+
+If none of the above methods is called, ValueMap should be used instead. +

+ +

Noncompliant Code Example

+
+public Object getProperty(Resource resource) {
+	ModifiableValueMap createdResourceProperties = resource.adaptTo(ModifiableValueMap.class); // Noncompliant ValueMap should be used
+	return createdResourceProperties.get("propertyName");
+}
+
+

Compliant Solution

+
+public Object getProperty(Resource resource) {
+	ValueMap createdResourceProperties = resource.getValueMap();
+	return createdResourceProperties.get("propertyName");
+}
+
diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-17.json b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-17.json new file mode 100644 index 00000000..84f40d83 --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-17.json @@ -0,0 +1,14 @@ +{ + "title": "No mutator methods invoked on ModifiableValueMap", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "10min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Critical", + "sqKey": "AEM-17" +} diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-18.html b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-18.html new file mode 100644 index 00000000..2b7fda0e --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-18.html @@ -0,0 +1,37 @@ +

+ The page.getContentResource() + is a method of the Page class + which allows you to get a Resource from the page.
+
+ It is possible to get a null if a jcr:content node does not exist in the repository. +

+

+ Lack of jrc:content is a quite common situation and occurs when one publishes a deeply nested page without publishing its parents first. + In that case parent pages will be published without jrc:content node. +

+

+ Therefore, you should always null check the return value of getContentResource() +

+ +

Noncompliant Code Example

+
+public ValueMap getProperty(Page page) {
+	return page.getContentResource().getValueMap();
+}
+
+

Compliant Solution

+
+public ValueMap getProperty(Page page) {
+	if (page.getContentResource != null) {
+	  return page.getContentResource.getValueMap();
+	}
+	return ValueMap.EMPTY;
+}
+
+

or

+
+public ValueMap getProperty(Page page) {
+    Optional<Resource> contentResource = Optional.ofNullable(page.getContentResource());
+    return contentResource.map(Resource::getValueMap).orElse(ValueMap.EMPTY);
+}
+
diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-18.json b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-18.json new file mode 100644 index 00000000..d3ca0763 --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-18.json @@ -0,0 +1,14 @@ +{ + "title": "Always null check the returned value of Page.getContentResource() method", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "AEM-18" +} diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-19.html b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-19.html new file mode 100644 index 00000000..24c1b379 --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-19.html @@ -0,0 +1,23 @@ +

+ The SlingQuery + is a Sling resource tree traversal tool inspired by the jQuery JavaScript API. +

+

+ SearchStrategy can have negative performance impact if mismatched.

+ Therefore developer should always make informed decision and define strategy explicitly. +

+ +

Noncompliant Code Example

+
+private void strategyNotDefined(Resource resource) {
+		SlingQuery sq = $(resource);
+		sq.find();
+	}
+
+

Compliant Solution

+
+private void strategyDefined(Resource resource) {
+		SlingQuery sq = $(resource).searchStrategy(SearchStrategy.BFS);
+		sq.find();
+	}
+
diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-19.json b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-19.json new file mode 100644 index 00000000..5d8e19fd --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-19.json @@ -0,0 +1,14 @@ +{ + "title": "Implicit search strategy used in Sling Query", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "30min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "AEM-19" +} diff --git a/src/main/resources/rules/AEM-2.md b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-2.html similarity index 80% rename from src/main/resources/rules/AEM-2.md rename to src/main/resources/org/sonar/l10n/java/rules/java/AEM-2.html index 47b46fa8..ce768b66 100644 --- a/src/main/resources/rules/AEM-2.md +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-2.html @@ -1,6 +1,6 @@ -Use constants available in AEM instead of repeating inline literals. -== Noncompliant Code Example -`` +

Use constants available in AEM instead of repeating inline literals.

+

Noncompliant Code Example

+
 @SlingServlet(
         resourceTypes = { "some/resource/path" },
         selectors = { "inspect", "install" },
@@ -8,9 +8,9 @@
         methods = { "POST" } // Noncompliant; Use predefined constant available in org.apache.sling.api.servlets.HttpConstants.METHOD_POST
 )
 public class ComponentServlet extends SlingAllMethodsServlet {
-``
-== Compliant Solution
-``
+
+

Compliant Solution

+
 import org.apache.sling.api.servlets.HttpConstants;
 // ...
 @SlingServlet(
@@ -20,4 +20,4 @@
         methods = { HttpConstants.METHOD_POST }
 )
 public class ComponentServlet extends SlingAllMethodsServlet {
-``
+
diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-2.json b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-2.json new file mode 100644 index 00000000..5d35e53f --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-2.json @@ -0,0 +1,14 @@ +{ + "title": "Use predefined constant instead of hardcoded value.", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "AEM-2" +} diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-20.html b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-20.html new file mode 100644 index 00000000..45a337ef --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-20.html @@ -0,0 +1,36 @@ +

+ The ResourceResolver + should be initialised in + try-with-resources block + which ensures that it will be automatically closed because of the + Autocloseable interface. +

+

+ Therefore, you should always initialise ResourceResolver in try-with-resources block +

+ +

Noncompliant Code Example

+
+protected void getResourceResolver() {
+    ResourceResolver resourceResolver = null;
+    try {
+        resourceResolver = resourceResolverFactory.getServiceResourceResolver(null); // Noncompliant
+    } catch (LoginException e) {
+        System.out.println("something went wrong");
+    } finally {
+        if (resourceResolver != null) {
+            //resourceResolver.close();
+        }
+    }
+}
+
+

Compliant Solution

+
+private void getResourceResolver() {
+    try (ResourceResolver resourceResolver = resourceResolverFactory.getServiceResourceResolver(null)) {
+        resourceResolver.getResource("path/to/resource");
+    } catch (LoginException e) {
+        System.out.println("something went wrong");
+    }
+}
+
diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-20.json b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-20.json new file mode 100644 index 00000000..2f3272f0 --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-20.json @@ -0,0 +1,14 @@ +{ + "title": "ResourceResolver can be closed using try-with-resources Java 7 feature.", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "10min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Info", + "sqKey": "AEM-20" +} diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-3.html b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-3.html new file mode 100644 index 00000000..409721a4 --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-3.html @@ -0,0 +1,30 @@ +

+ It is not safe to keep session based object as a field in Servlet, Filter, or EventHandler. + As well as any Declarative Services component. Rule checks for the occurrence of any instance or static fields of + following types: +

+
    +
  • org.apache.sling.api.resource.ResourceResolver
  • +
  • javax.jcr.Session
  • +
  • com.day.cq.wcm.api.PageManager
  • +
+

Noncompliant Code Example

+
+public class ComponentsServlet extends SlingSafeMethodsServlet {
+
+    public static final ResourceResolver staticResolver; // Noncompliant
+
+    private ResourceResolver resolver; // Noncompliant
+
+    public ResourceResolver publicResolver; // Noncompliant
+
+    private PageManager pageManager; // Noncompliant
+
+    private Session session; // Noncompliant
+
+
+
+public class ComponentsFilter implements Filter {
+
+    private PageManager pageManager; // Noncompliant
+
diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-3.json b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-3.json new file mode 100644 index 00000000..f1f9af9f --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-3.json @@ -0,0 +1,15 @@ +{ + "title": "Non-thread safe object used as a field of Servlet / Filter etc.", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "1h" + }, + "tags": [ + "bug", + "aem" + ], + "defaultSeverity": "Critical", + "sqKey": "AEM-3" +} diff --git a/src/main/resources/rules/AEM-6.md b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-6.html similarity index 53% rename from src/main/resources/rules/AEM-6.md rename to src/main/resources/org/sonar/l10n/java/rules/java/AEM-6.html index a1e33b9d..5720a379 100644 --- a/src/main/resources/rules/AEM-6.md +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-6.html @@ -1,23 +1,29 @@ -Resource Resolver has a life cycle which begins with the creation of the Resource Resolver using any of the factory methods and ends with calling the ``close()`` method. It is very important to call the ``close()`` method once the resource resolver is not used any more to ensure any system resources are properly clean up. -== Noncompliant Code Example -`` +

+ Resource Resolver has a life cycle which begins with the creation of the Resource Resolver using any of the factory + methods and ends with calling the close() method. It is very important to call the close() + method once the resource resolver is not used any more to ensure any system resources are properly clean up. +

+ +

Noncompliant Code Example

+
 try {
     ResourceResolver resolver = resourceResolverFactory.getResourceResolver(authenticationInfoMap); // Noncompliant; resourceResolver should be closed in finally block
     // ...
 } catch (Exception e) {
     // ...
 }
-``
-``
+
+
+
 try {
     ResourceResolver resolver = resourceResolverFactory.getResourceResolver(authenticationInfoMap); // Noncompliant; resourceResolver should be closed in finally block
     resolver.close();
 } catch (Exception e) {
     // ...
 }
-``
-== Compliant Solution
-``
+
+

Compliant Solution

+
 ResourceResolver resolver = null;
 try {
     resolver = resourceResolverFactory.getResourceResolver(authenticationInfoMap);
@@ -29,6 +35,6 @@
         resolver.close();
     }
 }
-``
-== See
-[ResourceResolver Javadoc](https://sling.apache.org/apidocs/sling6/org/apache/sling/api/resource/ResourceResolver.html)
+
+

See

+ResourceResolver Javadoc diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-6.json b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-6.json new file mode 100644 index 00000000..606a138b --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-6.json @@ -0,0 +1,14 @@ +{ + "title": "ResourceResolver should be closed in finally block.", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "15min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Critical", + "sqKey": "AEM-6" +} diff --git a/src/main/resources/rules/AEM-7.md b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-7.html similarity index 55% rename from src/main/resources/rules/AEM-7.md rename to src/main/resources/org/sonar/l10n/java/rules/java/AEM-7.html index 355ca057..4b811a3d 100644 --- a/src/main/resources/rules/AEM-7.md +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-7.html @@ -1,16 +1,19 @@ -Manually created ``Session`` should be logged out after it is no longer needed. The ``logout()`` method releases all resources associated with ``Session``. -== Noncompliant Code Example -`` +

+ Manually created Session should be logged out after it is no longer needed. The logout() method releases all resources associated with Session. +

+ +

Noncompliant Code Example

+
 Session session = null;
 try {
 	session = repository.loginService("myService", null);
 	// ...
 } catch (RepositoryException e) {
 	// ...
-} 
-``
-== Compliant Solution
-``
+}
+
+

Compliant Solution

+
 Session session = null;
 try {
 	session = repository.loginService("myService", null);
@@ -22,4 +25,4 @@
         session.logout();
     }
 }
-``
\ No newline at end of file
+
diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-7.json b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-7.json new file mode 100644 index 00000000..5b6338fb --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-7.json @@ -0,0 +1,14 @@ +{ + "title": "Session should be logged out in finally block.", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "10min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Critical", + "sqKey": "AEM-7" +} diff --git a/src/main/resources/rules/AEM-8.md b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-8.html similarity index 72% rename from src/main/resources/rules/AEM-8.md rename to src/main/resources/org/sonar/l10n/java/rules/java/AEM-8.html index dc56fe1e..a7d9b044 100644 --- a/src/main/resources/rules/AEM-8.md +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-8.html @@ -1,6 +1,7 @@ -Prefer cleaner ``@SlingServlet`` annotation over ``@Properties`` approach. Do not mix up both approaches. -== Noncompliant Code Example -`` +

Prefer cleaner @SlingServlet annotation over @Properties approach. Do not mix up both approaches.

+ +

Noncompliant Code Example

+
 @Component
 @Service(value = javax.servlet.Servlet.class)
 @Properties({
@@ -9,13 +10,13 @@
         @Property(name = "sling.servlet.extensions", value = { "tab" }),
         @Property(name = "sling.servlet.methods", value = { HttpConstants.METHOD_GET })
 })
-``
-== Compliant Solution
-``
+
+

Compliant Solution

+
 @SlingServlet(
         resourceTypes = "some/resource/path",
         selectors = "selector",
         extensions = "tab",
         methods = HttpConstants.METHOD_GET
 )
-``
\ No newline at end of file
+
diff --git a/src/main/resources/org/sonar/l10n/java/rules/java/AEM-8.json b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-8.json new file mode 100644 index 00000000..27a2cc55 --- /dev/null +++ b/src/main/resources/org/sonar/l10n/java/rules/java/AEM-8.json @@ -0,0 +1,14 @@ +{ + "title": "Prefer cleaner @SlingServlet annotation.", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "10min" + }, + "tags": [ + "aem" + ], + "defaultSeverity": "Minor", + "sqKey": "AEM-8" +} diff --git a/src/main/resources/rules/AEM-11.md b/src/main/resources/rules/AEM-11.md deleted file mode 100644 index 16fa3448..00000000 --- a/src/main/resources/rules/AEM-11.md +++ /dev/null @@ -1,30 +0,0 @@ -Administrative access to the resource tree and JCR Repository by means of usage of ``ResourceResolverFactory.getAdministrativeResourceResolver`` and ``SlingRepository.loginAdministrative`` has been deprecated. -Use ``ResourceResolverFactory.getServiceResourceResolver`` or ``SlingRepository.loginService`` respectively. -== Noncompliant Code Example -`` -ResourceResolver resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(credentials); -`` -`` -Session session = slingRepository.loginAdministrative(workspace); -`` -== Compliant Solution -`` -try (ResourceResolver resourceResolver = resolverFactory.getServiceResourceResolver(null)) { - ... -} -`` -or -`` -Map param = new HashMap(); -param.put(ResourceResolverFactory.SUBSERVICE, "sub service name"); -try (ResourceResolver resourceResolver = resolverFactory.getServiceResourceResolver(param)) { - ... -} -`` -or -`` -Session session = slingRepository.loginService(subServiceName, workspace); -`` -== See -[ResourceResolverFactory Javadoc](https://docs.adobe.com/docs/en/aem/6-0/develop/ref/javadoc/org/apache/sling/api/resource/ResourceResolverFactory.html#getAdministrativeResourceResolver%28java.util.Map%29) -[Service Authentication](http://sling.apache.org/documentation/the-sling-engine/service-authentication.html) diff --git a/src/main/resources/rules/AEM-17.md b/src/main/resources/rules/AEM-17.md deleted file mode 100644 index d9e66e8d..00000000 --- a/src/main/resources/rules/AEM-17.md +++ /dev/null @@ -1,28 +0,0 @@ -The [`ModifiableValueMap`](https://sling.apache.org/apidocs/sling7/org/apache/sling/api/resource/ModifiableValueMap.html) is an extension -of the `ValueMap` which allows to modify and persist properties. -It is checking user permissions and returns `null` if the user has no permission to write. - -The modifiable value map is only changeable through any of the following methods: -- `put(String, Object)` -- `putAll(java.util.Map)` -- `remove(Object)` - -If none of the above methods is called, `ValueMap` should be used instead. - -== Noncompliant Code Example - -`` -public Object getProperty(Resource resource) { - ModifiableValueMap createdResourceProperties = resource.adaptTo(ModifiableValueMap.class); // Noncompliant ValueMap should be used - return createdResourceProperties.get("propertyName"); -} -`` - -== Compliant Solution - -`` -public Object getProperty(Resource resource) { - ValueMap createdResourceProperties = resource.getValueMap(); - return createdResourceProperties.get("propertyName"); -} -`` diff --git a/src/main/resources/rules/AEM-18.md b/src/main/resources/rules/AEM-18.md deleted file mode 100644 index 4f7a73ce..00000000 --- a/src/main/resources/rules/AEM-18.md +++ /dev/null @@ -1,37 +0,0 @@ -The [`page.getContentResource()`](https://helpx.adobe.com/experience-manager/6-3/sites/developing/using/reference-materials/javadoc/com/day/cq/wcm/api/Page.html#getContentResource()) -is a method of the [`Page` class](https://helpx.adobe.com/experience-manager/6-3/sites/developing/using/reference-materials/diff-previous/changes/com.day.cq.wcm.api.Page.html) -which allows you to get a Resource from the page. -It is possible to get a `null` if a jcr:content node does not exist in the repository. - -Lack of 'jrc:content' is a quite common situation and occurs when one publishes a deeply nested page without publishing its parents first. -In that case parent pages will be published without `jcr:content` node. - -Therefore, you should always null check the return value of 'getContentResource()' - -== Noncompliant Code Example - -`` -public ValueMap getProperty(Page page) { - return page.getContentResource().getValueMap(); -} -`` - -== Compliant Solution - -`` -public ValueMap getProperty(Page page) { - if (page.getContentResource != null) { - return page.getContentResource.getValueMap(); - } - return ValueMap.EMPTY; -} -`` - -or - -`` -public ValueMap getProperty(Page page) { - Optional contentResource = Optional.ofNullable(page.getContentResource()); - return contentResource.map(Resource::getValueMap).orElse(ValueMap.EMPTY); -} -`` diff --git a/src/main/resources/rules/AEM-19.md b/src/main/resources/rules/AEM-19.md deleted file mode 100644 index c654db04..00000000 --- a/src/main/resources/rules/AEM-19.md +++ /dev/null @@ -1,23 +0,0 @@ -The [`SlingQuery`](https://sling.apache.org/documentation/bundles/sling-query.html) -is a Sling resource tree traversal tool inspired by the jQuery JavaScript API. - -`SearchStrategy` can have negative performance impact if mismatched. -Therefore developer should always make informed decision and define strategy explicitly. - -== Noncompliant Code Example - -`` -private void strategyNotDefined(Resource resource) { - SlingQuery sq = $(resource); - sq.find(); - } -`` - -== Compliant Solution - -`` -private void strategyDefined(Resource resource) { - SlingQuery sq = $(resource).searchStrategy(SearchStrategy.BFS); - sq.find(); - } -`` diff --git a/src/main/resources/rules/AEM-20.md b/src/main/resources/rules/AEM-20.md deleted file mode 100644 index adc12a41..00000000 --- a/src/main/resources/rules/AEM-20.md +++ /dev/null @@ -1,34 +0,0 @@ -The [`ResourceResolver`](https://sling.apache.org/apidocs/sling10/org/apache/sling/api/resource/ResourceResolver.html) -should be initialised in [`try-with-resources` block](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) -which ensures that it will be automatically closed because of the [`Autocloseable` interface](https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html). - - Therefore, you should always initialise ResourceResolver in 'try-with-resources' block - - == Noncompliant Code Example - -`` -protected void getResourceResolver() { - ResourceResolver resourceResolver = null; - try { - resourceResolver = resourceResolverFactory.getServiceResourceResolver(null); // Noncompliant - } catch (LoginException e) { - System.out.println("something went wrong"); - } finally { - if (resourceResolver != null) { - //resourceResolver.close(); - } - } -} -`` - - == Compliant Solution - -`` -private void getResourceResolver() { - try (ResourceResolver resourceResolver = resourceResolverFactory.getServiceResourceResolver(null)) { - resourceResolver.getResource("path/to/resource"); - } catch (LoginException e) { - System.out.println("something went wrong"); - } -} -`` diff --git a/src/main/resources/rules/AEM-3.md b/src/main/resources/rules/AEM-3.md deleted file mode 100644 index 5d48bdb4..00000000 --- a/src/main/resources/rules/AEM-3.md +++ /dev/null @@ -1,24 +0,0 @@ -It is not safe to keep session based object as a field in ``Servlet``, ``Filter``, or ``EventHandler``. -As well as any Declarative Services component. Rule checks for the occurrence of any instance or static fields of following types: -* org.apache.sling.api.resource.ResourceResolver -* javax.jcr.Session -* com.day.cq.wcm.api.PageManager -== Noncompliant Code Example -`` -public class ComponentsServlet extends SlingSafeMethodsServlet { - - public static final ResourceResolver staticResolver; // Noncompliant - - private ResourceResolver resolver; // Noncompliant - - public ResourceResolver publicResolver; // Noncompliant - - private PageManager pageManager; // Noncompliant - - private Session session; // Noncompliant -`` -`` -public class ComponentsFilter implements Filter { - - private PageManager pageManager; // Noncompliant -`` diff --git a/src/main/resources/rules/HTL-0.md b/src/main/resources/rules/HTL-0.md deleted file mode 100644 index 38694697..00000000 --- a/src/main/resources/rules/HTL-0.md +++ /dev/null @@ -1 +0,0 @@ -Compilation error \ No newline at end of file diff --git a/src/main/resources/rules/HTL-1.md b/src/main/resources/rules/HTL-1.md deleted file mode 100644 index 1421fd5d..00000000 --- a/src/main/resources/rules/HTL-1.md +++ /dev/null @@ -1,14 +0,0 @@ -Always Place HTL Attributes After the Ones that are Part of the Markup -It's easier to understand HTL code if the attributes processed server-side are visually separated from the ones used at the front-end. - -== Noncompliant Code Example - -`` -
// Bad - mixing HTL attributes with other ones -`` - -== Compliant Solution - -`` -
// Good - HTL-specific attributes grouped at the end of the element -`` diff --git a/src/main/resources/rules/HTL-10.md b/src/main/resources/rules/HTL-10.md deleted file mode 100644 index 6d0b7b48..00000000 --- a/src/main/resources/rules/HTL-10.md +++ /dev/null @@ -1,14 +0,0 @@ -If it's not possible to use an existing element, prefer sly tags over introducing superfluous markup that renders on the page. - -== Noncompliant Code Examples - -`` -
-
-`` - -== Compliant Solution - -`` - -`` diff --git a/src/main/resources/rules/HTL-11.md b/src/main/resources/rules/HTL-11.md deleted file mode 100644 index 5ae5704b..00000000 --- a/src/main/resources/rules/HTL-11.md +++ /dev/null @@ -1,23 +0,0 @@ -Use existing HTML elements instead of adding extra sly tags. - -== Noncompliant Code Example - -`` - -
-

${model.headline}

-

${model.text}

-
-
-`` - -== Compliant Solution - -`` -
-

${model.headline}

-

${model.text}

-
-`` diff --git a/src/main/resources/rules/HTL-12.md b/src/main/resources/rules/HTL-12.md deleted file mode 100644 index 2f3c51c7..00000000 --- a/src/main/resources/rules/HTL-12.md +++ /dev/null @@ -1,26 +0,0 @@ -Use the most restrictive HTL context possible. - -== Noncompliant Code Example -``
`` - -== Compliant Solution -``
`` - -Available markup context: -* html - Use this in case you want to output HTMLRemoves markup that may contain XSS risks -* text - Use this for simple HTML contentEncodes all HTML -* elementName - Allows only element names that are white-listed, outputs 'div' otherwise - -* attributeName - Outputs nothing if the value doesn't correspond to the HTML attribute name syntaxdoesn't allow 'style' and 'on*' attributes -* attribute - Applies HTML attribute escaping -* uri - Outputs nothing if the value contains XSS risks -* scriptToken - Outputs nothing if the value doesn't correspond to an Identifier, String literal or Numeric literal JavaScript token -* scriptString - Applies JavaScript string escaping -* scriptComment - Context for Javascript block comments. Outputs nothing if value is trying to break out of the comment context -* scriptRegExp - Applies JavaScript regular expression escaping -* styleToken - Outputs nothing if the value doesn't correspond to the CSS token syntax -* styleString - Applies CSS string escaping -* styleComment - Context for CSS comments. Outputs nothing if value is trying to break out of the comment context -* comment - Applies HTML comment escaping -* number - Outputs zero if the value is not a number -* unsafe - Use this at your own risk, this disables XSS protection completely -Source : https://github.com/adobe/htl-spec/blob/master/SPECIFICATION.md#121-display-context diff --git a/src/main/resources/rules/HTL-13.md b/src/main/resources/rules/HTL-13.md deleted file mode 100644 index 7dda5451..00000000 --- a/src/main/resources/rules/HTL-13.md +++ /dev/null @@ -1,16 +0,0 @@ -Avoid using 'unsafe' display context, it disables XSS protection completely. - -== Noncompliant Code Example -`` -
-

${model.text}

-
-`` diff --git a/src/main/resources/rules/HTL-14.md b/src/main/resources/rules/HTL-14.md deleted file mode 100644 index 9d69f17c..00000000 --- a/src/main/resources/rules/HTL-14.md +++ /dev/null @@ -1,14 +0,0 @@ -HTL expressions in HTML comments should have defined context. - -== Noncompliant Code Example - -`` - -`` - - -== Compliant Solution - -`` - -`` diff --git a/src/main/resources/rules/HTL-15.md b/src/main/resources/rules/HTL-15.md deleted file mode 100644 index 92a7a6ba..00000000 --- a/src/main/resources/rules/HTL-15.md +++ /dev/null @@ -1,17 +0,0 @@ -Use Camel Case in identifiers: - * variable names - * template names - -== Noncompliant Code Example - -`` - - -`` - -== Compliant Solution - -`` - - -`` \ No newline at end of file diff --git a/src/main/resources/rules/HTL-16.md b/src/main/resources/rules/HTL-16.md deleted file mode 100644 index 4c72bb9f..00000000 --- a/src/main/resources/rules/HTL-16.md +++ /dev/null @@ -1,12 +0,0 @@ -HTL elements are automatically unwrapped. - -== Noncompliant Code Example -`` -Caption -`` -== Compliant Solution -`` -Caption - -Caption -`` diff --git a/src/main/resources/rules/HTL-2.md b/src/main/resources/rules/HTL-2.md deleted file mode 100644 index fe290c05..00000000 --- a/src/main/resources/rules/HTL-2.md +++ /dev/null @@ -1,13 +0,0 @@ -HTL Templates should be placed in separate files. This helps to understand which code is meant to render a component and which code is re-used as a template. Additionally, component-specific code can be safely removed. It should be immediately obvious whether or not some code is re-used across the codebase. - -== Noncompliant Code Example - -`` - - -
- -`` diff --git a/src/main/resources/rules/HTL-3.md b/src/main/resources/rules/HTL-3.md deleted file mode 100644 index abcdbea2..00000000 --- a/src/main/resources/rules/HTL-3.md +++ /dev/null @@ -1,22 +0,0 @@ -HTL provides implicit variables in data-sly-list and data-sly-repeat blocks. -Try to avoid them and use explicit names clarifying the role of the objects instead. - - == Noncompliant Code Example - -`` - -`` - -== Compliant Solution - -`` - -`` diff --git a/src/main/resources/rules/HTL-4.md b/src/main/resources/rules/HTL-4.md deleted file mode 100644 index bf4b53a3..00000000 --- a/src/main/resources/rules/HTL-4.md +++ /dev/null @@ -1,23 +0,0 @@ -Always try to re-use existing conditions, so the code is more readable. - -== Noncompliant Code Example - -`` - -
- Some text -
-
- -`` - -== Compliant Solution - -`` - -
- Some text -
-
- -`` diff --git a/src/main/resources/rules/HTL-5.md b/src/main/resources/rules/HTL-5.md deleted file mode 100644 index 73f1e7a9..00000000 --- a/src/main/resources/rules/HTL-5.md +++ /dev/null @@ -1,13 +0,0 @@ -Always use HTL style of commenting - -== Noncompliant Code Example - -`` - -`` - -== Compliant Solution - -`` - -`` diff --git a/src/main/resources/rules/HTL-6.md b/src/main/resources/rules/HTL-6.md deleted file mode 100644 index 336da124..00000000 --- a/src/main/resources/rules/HTL-6.md +++ /dev/null @@ -1,17 +0,0 @@ -HTL uses uri display context as default for src, poster, manifest, href, formaction, data, cite, action attributes. Explicit display context definition should be removed. - -== Noncompliant Code Example - -`` -${model.imageAlt @ context='attribute'} -`` - -== Compliant Solution - -`` -${model.imageAlt} - -
- ${'http://www.example.org/search?s=1&q=htl' @ context='uri'} -
-`` diff --git a/src/main/resources/rules/HTL-7.md b/src/main/resources/rules/HTL-7.md deleted file mode 100644 index d9f58593..00000000 --- a/src/main/resources/rules/HTL-7.md +++ /dev/null @@ -1,29 +0,0 @@ -For style and script tags display context definition is mandatory. - -== Noncompliant Code Example - -`` - - - -`` - -== Compliant Solution - -`` - - - -`` diff --git a/src/main/resources/rules/HTL-8.md b/src/main/resources/rules/HTL-8.md deleted file mode 100644 index 863ea054..00000000 --- a/src/main/resources/rules/HTL-8.md +++ /dev/null @@ -1,13 +0,0 @@ -In HTL event attributes must contain display context definition"; - -== Noncompliant Code Example - -`` -Link -`` - -== Compliant Solution - -`` -Link -`` diff --git a/src/main/resources/rules/HTL-9.md b/src/main/resources/rules/HTL-9.md deleted file mode 100644 index 9a9e3044..00000000 --- a/src/main/resources/rules/HTL-9.md +++ /dev/null @@ -1,13 +0,0 @@ -For inline styles display context is mandatory - -== Noncompliant Code Example - -`` -Link -`` - -== Compliant Solution - -`` -Link -`` diff --git a/src/main/script/prepareResources.groovy b/src/main/script/prepareResources.groovy index f91a92f2..bceca8f6 100644 --- a/src/main/script/prepareResources.groovy +++ b/src/main/script/prepareResources.groovy @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/java/ContentResourceShouldBeNullCheckedCheck.java b/src/test/files/checks/java/ContentResourceShouldBeNullCheckedCheck.java deleted file mode 100644 index e1477451..00000000 --- a/src/test/files/checks/java/ContentResourceShouldBeNullCheckedCheck.java +++ /dev/null @@ -1,143 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.example; - -import com.adobe.cq.commerce.common.ValueMapDecorator; -import com.day.cq.wcm.api.Page; -import java.util.HashMap; -import java.util.Objects; -import java.util.Optional; -import org.apache.commons.lang3.ObjectUtils; -import org.apache.sling.api.resource.ModifiableValueMap; -import org.apache.sling.api.resource.Resource; -import org.apache.sling.api.resource.ValueMap; - -public class ContentResourceShouldBeNullCheckedCheck { - - private void contentResourceNotNullCheckedBeforeUsage(Resource resource) { - Page page = resource.adaptTo(Page.class); - Resource contentResourceA = page.getContentResource(); - Iterable children = contentResourceA.getChildren(); // Noncompliant - } - - private void notSafeUseOfResourceAfterIfWithNullCheck(Resource resource) { - Page page = resource.adaptTo(Page.class); - Resource contentResource = page.getContentResource("test"); - if (contentResource != null) { - // do something - } - Iterable children = contentResource.getChildren(); // Noncompliant - } - - private void nullCheckUsedOnDifferentResourceThanCheckedInIfStatement(Resource resource1, - Resource resource2) { - Page page1 = resource1.adaptTo(Page.class); - Page page2 = resource2.adaptTo(Page.class); - Resource contentResource1 = page1.getContentResource(); - Resource contentResource2 = page2.getContentResource("test"); - if (contentResource1 != null) { - Iterable children = contentResource2.getChildren(); // Noncompliant - } - } - - private void correctlyNullCheckedContentResource(Resource resource1, Resource resource2) { - Page page1 = resource1.adaptTo(Page.class); - Page page2 = resource2.adaptTo(Page.class); - Resource contentResource1 = page1.getContentResource(); - Resource contentResource2 = page2.getContentResource(); - Iterable children = null; - if (contentResource1 != null) { - children = contentResource1.getChildren(); - if (contentResource2 != null) { - children = contentResource1.getChildren(); - } - children = contentResource1.getChildren(); - } else if (contentResource2 != null) { - children = contentResource2.getChildren(); - } - } - - private void directlyCallMethodOnGetContentResourceReturn(Resource resource) { - Page page = resource.adaptTo(Page.class); - ValueMap map = page.getContentResource().getValueMap(); // Noncompliant - ModifiableValueMap modifiableValueMap = page.getContentResource().adaptTo(ModifiableValueMap.class); // Noncompliant - } - - private void useOfOptionalInCaseOfNullContentResource(Resource resource) { - Page page = resource.adaptTo(Page.class); - Optional contentResourceOptional = Optional.ofNullable(page.getContentResource()); - Iterable children = contentResourceOptional.get().getChildren(); - } - - private boolean contentResourceNullCheckWithImmediateReturn(Resource resource) { - Page page = resource.adaptTo(Page.class); - Resource contentResource = page.getContentResource(); - if (contentResource == null) { - return false; - } - contentResource.getValueMap(); - return true; - } - - private ValueMap checkForNullWithObjectsNonNull(Resource resource) { - ValueMap result = new ValueMapDecorator(new HashMap<>()); - Page page = resource.adaptTo(Page.class); - Resource pageResource = page.getContentResource("test"); - if (Objects.nonNull(pageResource)) { - result = pageResource.getValueMap(); - } - return result; - } - - private ValueMap checkForNullWithObjectsIsNull(Resource resource) { - ValueMap result = new ValueMapDecorator(new HashMap<>()); - Page page = resource.adaptTo(Page.class); - Resource pageResource = page.getContentResource("test"); - if (Objects.isNull(pageResource)) { - return result; - } else { - return pageResource.getValueMap(); - } - } - - private ValueMap checkForNullWithCommonsObjectUtilsAllNotNull(Resource resource) { - ValueMap result = new ValueMapDecorator(new HashMap<>()); - Page page = resource.adaptTo(Page.class); - Resource pageResource = page.getContentResource("test"); - if (ObjectUtils.allNotNull(pageResource)) { - result = pageResource.getValueMap(); - } - return result; - } - - private ValueMap checkForNonNullWithCommonsObjectUtilsAllNotNullMultipleResources(Resource resource) { - ValueMap result = new ValueMapDecorator(new HashMap<>()); - Page page = resource.adaptTo(Page.class); - Resource pageResource = page.getContentResource("test"); - Resource pageResource2 = page.getContentResource("test"); - Resource pageResource3 = page.getContentResource("test"); - if (ObjectUtils.allNotNull(pageResource, pageResource2)) { - result = pageResource.getValueMap(); - result = pageResource2.getValueMap(); - result = pageResource3.getValueMap(); // Noncompliant - } - return result; - } -} diff --git a/src/test/files/checks/htl/AvoidExtraSlyTagsCheck.html b/src/test/files/htl/AvoidExtraSlyTagsCheck.html similarity index 96% rename from src/test/files/checks/htl/AvoidExtraSlyTagsCheck.html rename to src/test/files/htl/AvoidExtraSlyTagsCheck.html index aa91f920..0cf240ec 100644 --- a/src/test/files/checks/htl/AvoidExtraSlyTagsCheck.html +++ b/src/test/files/htl/AvoidExtraSlyTagsCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/htl/AvoidUsingUnsafeDisplayContextCheck.html b/src/test/files/htl/AvoidUsingUnsafeDisplayContextCheck.html similarity index 95% rename from src/test/files/checks/htl/AvoidUsingUnsafeDisplayContextCheck.html rename to src/test/files/htl/AvoidUsingUnsafeDisplayContextCheck.html index 52d117df..fdce9c34 100644 --- a/src/test/files/checks/htl/AvoidUsingUnsafeDisplayContextCheck.html +++ b/src/test/files/htl/AvoidUsingUnsafeDisplayContextCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/htl/CamelCaseCheck.html b/src/test/files/htl/CamelCaseCheck.html similarity index 96% rename from src/test/files/checks/htl/CamelCaseCheck.html rename to src/test/files/htl/CamelCaseCheck.html index 68901b9e..f588f875 100644 --- a/src/test/files/checks/htl/CamelCaseCheck.html +++ b/src/test/files/htl/CamelCaseCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/htl/DefineDisplayContextInEventAttributes.html b/src/test/files/htl/DefineDisplayContextInEventAttributes.html similarity index 94% rename from src/test/files/checks/htl/DefineDisplayContextInEventAttributes.html rename to src/test/files/htl/DefineDisplayContextInEventAttributes.html index 0c3109df..00307988 100644 --- a/src/test/files/checks/htl/DefineDisplayContextInEventAttributes.html +++ b/src/test/files/htl/DefineDisplayContextInEventAttributes.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/htl/DefineDisplayContextInInlineStylesCheck.html b/src/test/files/htl/DefineDisplayContextInInlineStylesCheck.html similarity index 93% rename from src/test/files/checks/htl/DefineDisplayContextInInlineStylesCheck.html rename to src/test/files/htl/DefineDisplayContextInInlineStylesCheck.html index b3cc6df8..a71e761f 100644 --- a/src/test/files/checks/htl/DefineDisplayContextInInlineStylesCheck.html +++ b/src/test/files/htl/DefineDisplayContextInInlineStylesCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/htl/DefineDisplayContextInScriptsAndStylesCheck.html b/src/test/files/htl/DefineDisplayContextInScriptsAndStylesCheck.html similarity index 94% rename from src/test/files/checks/htl/DefineDisplayContextInScriptsAndStylesCheck.html rename to src/test/files/htl/DefineDisplayContextInScriptsAndStylesCheck.html index c924ee22..d005d5a5 100644 --- a/src/test/files/checks/htl/DefineDisplayContextInScriptsAndStylesCheck.html +++ b/src/test/files/htl/DefineDisplayContextInScriptsAndStylesCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/htl/DisplayContextInConditionalCommentsCheck.html b/src/test/files/htl/DisplayContextInConditionalCommentsCheck.html similarity index 94% rename from src/test/files/checks/htl/DisplayContextInConditionalCommentsCheck.html rename to src/test/files/htl/DisplayContextInConditionalCommentsCheck.html index 7fa0a6e9..7d944ce6 100644 --- a/src/test/files/checks/htl/DisplayContextInConditionalCommentsCheck.html +++ b/src/test/files/htl/DisplayContextInConditionalCommentsCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/htl/Empty.html b/src/test/files/htl/Empty.html new file mode 100644 index 00000000..fa0d417f --- /dev/null +++ b/src/test/files/htl/Empty.html @@ -0,0 +1,21 @@ + diff --git a/src/test/files/checks/htl/ExplicitNamesInLoopsCheck.html b/src/test/files/htl/ExplicitNamesInLoopsCheck.html similarity index 96% rename from src/test/files/checks/htl/ExplicitNamesInLoopsCheck.html rename to src/test/files/htl/ExplicitNamesInLoopsCheck.html index f2cf6b2b..f776be5f 100644 --- a/src/test/files/checks/htl/ExplicitNamesInLoopsCheck.html +++ b/src/test/files/htl/ExplicitNamesInLoopsCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/htl/HtlAttributesShouldBeAtTheEndCheck.html b/src/test/files/htl/HtlAttributesShouldBeAtTheEndCheck.html similarity index 92% rename from src/test/files/checks/htl/HtlAttributesShouldBeAtTheEndCheck.html rename to src/test/files/htl/HtlAttributesShouldBeAtTheEndCheck.html index 00765b87..678aa996 100644 --- a/src/test/files/checks/htl/HtlAttributesShouldBeAtTheEndCheck.html +++ b/src/test/files/htl/HtlAttributesShouldBeAtTheEndCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/htl/HtlCommentsCheck.html b/src/test/files/htl/HtlCommentsCheck.html similarity index 100% rename from src/test/files/checks/htl/HtlCommentsCheck.html rename to src/test/files/htl/HtlCommentsCheck.html diff --git a/src/test/files/checks/htl/NamingAndReusingConditionsCheck.html b/src/test/files/htl/NamingAndReusingConditionsCheck.html similarity index 96% rename from src/test/files/checks/htl/NamingAndReusingConditionsCheck.html rename to src/test/files/htl/NamingAndReusingConditionsCheck.html index c72bb748..bf32f1a8 100644 --- a/src/test/files/checks/htl/NamingAndReusingConditionsCheck.html +++ b/src/test/files/htl/NamingAndReusingConditionsCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/htl/PlaceTemplatesInSeparateFilesCheck.html b/src/test/files/htl/PlaceTemplatesInSeparateFilesCheck.html similarity index 97% rename from src/test/files/checks/htl/PlaceTemplatesInSeparateFilesCheck.html rename to src/test/files/htl/PlaceTemplatesInSeparateFilesCheck.html index 5971d646..6087c186 100644 --- a/src/test/files/checks/htl/PlaceTemplatesInSeparateFilesCheck.html +++ b/src/test/files/htl/PlaceTemplatesInSeparateFilesCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/htl/SlyElementsAreAutomaticallyUnwrappedCheck.html b/src/test/files/htl/SlyElementsAreAutomaticallyUnwrappedCheck.html similarity index 93% rename from src/test/files/checks/htl/SlyElementsAreAutomaticallyUnwrappedCheck.html rename to src/test/files/htl/SlyElementsAreAutomaticallyUnwrappedCheck.html index 15675f60..4b5e6b39 100644 --- a/src/test/files/checks/htl/SlyElementsAreAutomaticallyUnwrappedCheck.html +++ b/src/test/files/htl/SlyElementsAreAutomaticallyUnwrappedCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/htl/UseDefaultDisplayContextCheck.html b/src/test/files/htl/UseDefaultDisplayContextCheck.html similarity index 94% rename from src/test/files/checks/htl/UseDefaultDisplayContextCheck.html rename to src/test/files/htl/UseDefaultDisplayContextCheck.html index f57025a7..d98b8835 100644 --- a/src/test/files/checks/htl/UseDefaultDisplayContextCheck.html +++ b/src/test/files/htl/UseDefaultDisplayContextCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/htl/UseMostRestrictiveHtlContextCheck.html b/src/test/files/htl/UseMostRestrictiveHtlContextCheck.html similarity index 92% rename from src/test/files/checks/htl/UseMostRestrictiveHtlContextCheck.html rename to src/test/files/htl/UseMostRestrictiveHtlContextCheck.html index 739de14a..b8a5753b 100644 --- a/src/test/files/checks/htl/UseMostRestrictiveHtlContextCheck.html +++ b/src/test/files/htl/UseMostRestrictiveHtlContextCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/htl/UseSlyTagsOverRedundantMarkupCheck.html b/src/test/files/htl/UseSlyTagsOverRedundantMarkupCheck.html similarity index 96% rename from src/test/files/checks/htl/UseSlyTagsOverRedundantMarkupCheck.html rename to src/test/files/htl/UseSlyTagsOverRedundantMarkupCheck.html index aabfc29a..e3e0e4c1 100644 --- a/src/test/files/checks/htl/UseSlyTagsOverRedundantMarkupCheck.html +++ b/src/test/files/htl/UseSlyTagsOverRedundantMarkupCheck.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/java/AdministrativeAccessUsageCheck.java b/src/test/files/java/AdministrativeAccessUsageCheck.java similarity index 97% rename from src/test/files/checks/java/AdministrativeAccessUsageCheck.java rename to src/test/files/java/AdministrativeAccessUsageCheck.java index 4719aea2..058dad75 100644 --- a/src/test/files/checks/java/AdministrativeAccessUsageCheck.java +++ b/src/test/files/java/AdministrativeAccessUsageCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,9 +17,11 @@ * limitations under the License. * #L% */ + import java.util.Map; import javax.jcr.RepositoryException; import javax.jcr.Session; + import org.apache.felix.scr.annotations.Reference; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.ResourceResolver; diff --git a/src/test/files/checks/java/AnnotationsConstantsCheck.java b/src/test/files/java/AnnotationsConstantsCheck.java similarity index 65% rename from src/test/files/checks/java/AnnotationsConstantsCheck.java rename to src/test/files/java/AnnotationsConstantsCheck.java index 08639c15..f7ef8462 100644 --- a/src/test/files/checks/java/AnnotationsConstantsCheck.java +++ b/src/test/files/java/AnnotationsConstantsCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import java.io.IOException; import javax.servlet.ServletException; + import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.sling.SlingServlet; @@ -29,14 +30,14 @@ import org.apache.sling.api.servlets.SlingAllMethodsServlet; @SlingServlet( - resourceTypes = {"some/resource/path"}, - selectors = {"inspect", "install"}, - extensions = {"json"}, - methods = {"POST"} // Noncompliant {{Use constant METHOD_POST from class org.apache.sling.api.servlets.HttpConstants instead of hardcoded value.}} + resourceTypes = {"some/resource/path"}, + selectors = {"inspect", "install"}, + extensions = {"json"}, + methods = {"POST"} // Noncompliant {{Use constant METHOD_POST from class org.apache.sling.api.servlets.HttpConstants instead of hardcoded value.}} ) @Properties({ - @Property(name = "service.vendor", value = ZenGardenConstants.VENDOR_NAME), // Noncompliant {{Use constant SERVICE_VENDOR from interface org.osgi.framework.Constants instead of hardcoded value.}} - @Property(name = "service.description", value = "Provides import process.") // Noncompliant {{Use constant SERVICE_DESCRIPTION from interface org.osgi.framework.Constants instead of hardcoded value.}} + @Property(name = "service.vendor", value = ZenGardenConstants.VENDOR_NAME), // Noncompliant {{Use constant SERVICE_VENDOR from interface org.osgi.framework.Constants instead of hardcoded value.}} + @Property(name = "service.description", value = "Provides import process.") // Noncompliant {{Use constant SERVICE_DESCRIPTION from interface org.osgi.framework.Constants instead of hardcoded value.}} }) public class AnnotationsConstantsCheck extends SlingAllMethodsServlet { @@ -44,12 +45,12 @@ public class AnnotationsConstantsCheck extends SlingAllMethodsServlet { @Override("Test") protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { } @Override("service.description") // Noncompliant {{Use constant SERVICE_DESCRIPTION from interface org.osgi.framework.Constants instead of hardcoded value.}} protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { } } diff --git a/src/test/files/checks/java/resourceresolver/AutoclosableResourceResolver.java b/src/test/files/java/AutoclosableResourceResolver.java similarity index 97% rename from src/test/files/checks/java/resourceresolver/AutoclosableResourceResolver.java rename to src/test/files/java/AutoclosableResourceResolver.java index c5162c9b..74fb5c39 100644 --- a/src/test/files/checks/java/resourceresolver/AutoclosableResourceResolver.java +++ b/src/test/files/java/AutoclosableResourceResolver.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ */ package com.example; -import java.util.Map; import java.util.List; import java.awt.Event; import jdk.nashorn.internal.ir.annotations.Reference; diff --git a/src/test/files/checks/java/ConstantsCheck.java b/src/test/files/java/ConstantsCheck.java similarity index 96% rename from src/test/files/checks/java/ConstantsCheck.java rename to src/test/files/java/ConstantsCheck.java index a0b56d8d..ffee1e22 100644 --- a/src/test/files/checks/java/ConstantsCheck.java +++ b/src/test/files/java/ConstantsCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/files/java/ContentResourceShouldBeNullCheckedCheck.java b/src/test/files/java/ContentResourceShouldBeNullCheckedCheck.java new file mode 100644 index 00000000..20de3cb0 --- /dev/null +++ b/src/test/files/java/ContentResourceShouldBeNullCheckedCheck.java @@ -0,0 +1,144 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.example; + +import com.adobe.cq.commerce.common.ValueMapDecorator; +import com.day.cq.wcm.api.Page; +import org.apache.commons.lang3.ObjectUtils; +import org.apache.sling.api.resource.ModifiableValueMap; +import org.apache.sling.api.resource.Resource; +import org.apache.sling.api.resource.ValueMap; + +import java.util.HashMap; +import java.util.Objects; +import java.util.Optional; + +public class ContentResourceShouldBeNullCheckedCheck { + + private void contentResourceNotNullCheckedBeforeUsage(Resource resource) { + Page page = resource.adaptTo(Page.class); + Resource contentResourceA = page.getContentResource(); + Iterable children = contentResourceA.getChildren(); // Noncompliant + } + + private void notSafeUseOfResourceAfterIfWithNullCheck(Resource resource) { + Page page = resource.adaptTo(Page.class); + Resource contentResource = page.getContentResource("test"); + if (contentResource != null) { + // do something + } + Iterable children = contentResource.getChildren(); // Noncompliant + } + + private void nullCheckUsedOnDifferentResourceThanCheckedInIfStatement(Resource resource1, + Resource resource2) { + Page page1 = resource1.adaptTo(Page.class); + Page page2 = resource2.adaptTo(Page.class); + Resource contentResource1 = page1.getContentResource(); + Resource contentResource2 = page2.getContentResource("test"); + if (contentResource1 != null) { + Iterable children = contentResource2.getChildren(); // Noncompliant + } + } + + private void correctlyNullCheckedContentResource(Resource resource1, Resource resource2) { + Page page1 = resource1.adaptTo(Page.class); + Page page2 = resource2.adaptTo(Page.class); + Resource contentResource1 = page1.getContentResource(); + Resource contentResource2 = page2.getContentResource(); + Iterable children = null; + if (contentResource1 != null) { + children = contentResource1.getChildren(); + if (contentResource2 != null) { + children = contentResource1.getChildren(); + } + children = contentResource1.getChildren(); + } else if (contentResource2 != null) { + children = contentResource2.getChildren(); + } + } + + private void directlyCallMethodOnGetContentResourceReturn(Resource resource) { + Page page = resource.adaptTo(Page.class); + ValueMap map = page.getContentResource().getValueMap(); // Noncompliant + ModifiableValueMap modifiableValueMap = page.getContentResource().adaptTo(ModifiableValueMap.class); // Noncompliant + } + + private void useOfOptionalInCaseOfNullContentResource(Resource resource) { + Page page = resource.adaptTo(Page.class); + Optional contentResourceOptional = Optional.ofNullable(page.getContentResource()); + Iterable children = contentResourceOptional.get().getChildren(); + } + + private boolean contentResourceNullCheckWithImmediateReturn(Resource resource) { + Page page = resource.adaptTo(Page.class); + Resource contentResource = page.getContentResource(); + if (contentResource == null) { + return false; + } + contentResource.getValueMap(); + return true; + } + + private ValueMap checkForNullWithObjectsNonNull(Resource resource) { + ValueMap result = new ValueMapDecorator(new HashMap<>()); + Page page = resource.adaptTo(Page.class); + Resource pageResource = page.getContentResource("test"); + if (Objects.nonNull(pageResource)) { + result = pageResource.getValueMap(); + } + return result; + } + + private ValueMap checkForNullWithObjectsIsNull(Resource resource) { + ValueMap result = new ValueMapDecorator(new HashMap<>()); + Page page = resource.adaptTo(Page.class); + Resource pageResource = page.getContentResource("test"); + if (Objects.isNull(pageResource)) { + return result; + } else { + return pageResource.getValueMap(); + } + } + + private ValueMap checkForNullWithCommonsObjectUtilsAllNotNull(Resource resource) { + ValueMap result = new ValueMapDecorator(new HashMap<>()); + Page page = resource.adaptTo(Page.class); + Resource pageResource = page.getContentResource("test"); + if (ObjectUtils.allNotNull(pageResource)) { + result = pageResource.getValueMap(); + } + return result; + } + + private ValueMap checkForNonNullWithCommonsObjectUtilsAllNotNullMultipleResources(Resource resource) { + ValueMap result = new ValueMapDecorator(new HashMap<>()); + Page page = resource.adaptTo(Page.class); + Resource pageResource = page.getContentResource("test"); + Resource pageResource2 = page.getContentResource("test"); + Resource pageResource3 = page.getContentResource("test"); + if (ObjectUtils.allNotNull(pageResource, pageResource2)) { + result = pageResource.getValueMap(); + result = pageResource2.getValueMap(); + result = pageResource3.getValueMap(); // Noncompliant + } + return result; + } +} diff --git a/src/test/files/checks/java/slingmodels/DefaultInjectionStrategyAnnotationCheck.java b/src/test/files/java/DefaultInjectionStrategyAnnotationCheck.java similarity index 96% rename from src/test/files/checks/java/slingmodels/DefaultInjectionStrategyAnnotationCheck.java rename to src/test/files/java/DefaultInjectionStrategyAnnotationCheck.java index 24bc03d0..eeeb310c 100644 --- a/src/test/files/checks/java/slingmodels/DefaultInjectionStrategyAnnotationCheck.java +++ b/src/test/files/java/DefaultInjectionStrategyAnnotationCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,13 @@ */ package com.example; -import javax.inject.Inject; import org.apache.sling.api.resource.Resource; import org.apache.sling.models.annotations.DefaultInjectionStrategy; import org.apache.sling.models.annotations.Model; import org.apache.sling.models.annotations.Optional; +import javax.inject.Inject; + @Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL) public class DefaultInjectionStrategyAnnotationCheck { diff --git a/src/test/files/checks/java/slingmodels/DefaultInjectionStrategyAnnotationCheckMultipleAdaptables.java b/src/test/files/java/DefaultInjectionStrategyAnnotationCheckMultipleAdaptables.java similarity index 96% rename from src/test/files/checks/java/slingmodels/DefaultInjectionStrategyAnnotationCheckMultipleAdaptables.java rename to src/test/files/java/DefaultInjectionStrategyAnnotationCheckMultipleAdaptables.java index 10839aaa..8981dadc 100644 --- a/src/test/files/checks/java/slingmodels/DefaultInjectionStrategyAnnotationCheckMultipleAdaptables.java +++ b/src/test/files/java/DefaultInjectionStrategyAnnotationCheckMultipleAdaptables.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,13 @@ */ package com.example; -import javax.inject.Inject; import org.apache.sling.api.resource.Resource; import org.apache.sling.models.annotations.DefaultInjectionStrategy; import org.apache.sling.models.annotations.Model; import org.apache.sling.models.annotations.Optional; +import javax.inject.Inject; + @Model(adaptables = {Resource.class, SlingHttpServletRequest.class}, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL) public class DefaultInjectionStrategyAnnotationCheckMultipleAdaptables { diff --git a/src/test/files/checks/java/LongResourceResolverEvenListenerError.java b/src/test/files/java/LongResourceResolverEvenListenerError.java similarity index 97% rename from src/test/files/checks/java/LongResourceResolverEvenListenerError.java rename to src/test/files/java/LongResourceResolverEvenListenerError.java index 1f1b31a8..5b6b61a8 100644 --- a/src/test/files/checks/java/LongResourceResolverEvenListenerError.java +++ b/src/test/files/java/LongResourceResolverEvenListenerError.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,11 +19,6 @@ */ package com.example; -import java.util.Map; -import javax.jcr.RepositoryException; -import javax.jcr.Session; -import javax.jcr.observation.EventIterator; -import javax.jcr.observation.EventListener; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; @@ -33,6 +28,12 @@ import org.apache.sling.api.resource.ResourceResolverFactory; import org.apache.sling.jcr.api.SlingRepository; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.observation.EventIterator; +import javax.jcr.observation.EventListener; +import java.util.Map; + @Component public class LongResourceResolverEvenListenerError implements EventListener { diff --git a/src/test/files/checks/java/LongSessionEventListener.java b/src/test/files/java/LongSessionEventListener.java similarity index 97% rename from src/test/files/checks/java/LongSessionEventListener.java rename to src/test/files/java/LongSessionEventListener.java index a231e0dc..68fb18f4 100644 --- a/src/test/files/checks/java/LongSessionEventListener.java +++ b/src/test/files/java/LongSessionEventListener.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,6 @@ */ package com.example; -import java.util.Map; -import javax.jcr.RepositoryException; -import javax.jcr.Session; -import javax.jcr.observation.EventIterator; -import javax.jcr.observation.EventListener; -import javax.jcr.observation.ObservationManager; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; @@ -34,6 +28,13 @@ import org.apache.sling.api.resource.ResourceResolverFactory; import org.apache.sling.jcr.api.SlingRepository; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.observation.EventIterator; +import javax.jcr.observation.EventListener; +import javax.jcr.observation.ObservationManager; +import java.util.Map; + @Component public class LongSessionEventListener implements EventListener { diff --git a/src/test/files/checks/java/LongSessionEventListenerError.java b/src/test/files/java/LongSessionEventListenerError.java similarity index 97% rename from src/test/files/checks/java/LongSessionEventListenerError.java rename to src/test/files/java/LongSessionEventListenerError.java index 2f4334a0..5a5f96e8 100644 --- a/src/test/files/checks/java/LongSessionEventListenerError.java +++ b/src/test/files/java/LongSessionEventListenerError.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,18 +19,19 @@ */ package com.example; -import java.util.Map; -import javax.jcr.RepositoryException; -import javax.jcr.Session; -import javax.jcr.observation.EventIterator; -import javax.jcr.observation.EventListener; -import javax.jcr.observation.ObservationManager; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.sling.jcr.api.SlingRepository; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.observation.EventIterator; +import javax.jcr.observation.EventListener; +import javax.jcr.observation.ObservationManager; +import java.util.Map; + @Component public class LongSessionEventListenerError implements EventListener { diff --git a/src/test/files/checks/java/LongSessionService.java b/src/test/files/java/LongSessionService.java similarity index 98% rename from src/test/files/checks/java/LongSessionService.java rename to src/test/files/java/LongSessionService.java index e0e2d7ee..89e6a4cd 100644 --- a/src/test/files/checks/java/LongSessionService.java +++ b/src/test/files/java/LongSessionService.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,6 @@ */ package com.example; -import java.util.Map; -import javax.jcr.RepositoryException; -import javax.jcr.Session; -import javax.jcr.observation.EventIterator; -import javax.jcr.observation.EventListener; -import javax.servlet.http.HttpServletRequest; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; @@ -37,6 +31,13 @@ import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.observation.EventIterator; +import javax.jcr.observation.EventListener; +import javax.servlet.http.HttpServletRequest; +import java.util.Map; + @Component public class LongSessionService implements EventListener { diff --git a/src/test/files/checks/java/ModifiableValueMapUsageCheck.java b/src/test/files/java/ModifiableValueMapUsageCheck.java similarity index 91% rename from src/test/files/checks/java/ModifiableValueMapUsageCheck.java rename to src/test/files/java/ModifiableValueMapUsageCheck.java index bb79ba3e..8fdfc95b 100644 --- a/src/test/files/checks/java/ModifiableValueMapUsageCheck.java +++ b/src/test/files/java/ModifiableValueMapUsageCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,11 @@ */ package com.example; -import java.util.Map; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.Resource; +import java.util.Map; + public class ModifiableValueMapUsageCheck { public Resource setProperty(Resource resource) { @@ -40,12 +41,12 @@ public Resource removeProperty(Resource resource) { } public Object getPropertyFromResource(Resource resource) { - ModifiableValueMap createdResourceProperties = resource.adaptTo(ModifiableValueMap.class); // Noncompliant ValueMap should be used + ModifiableValueMap createdResourceProperties = resource.adaptTo(ModifiableValueMap.class); // Noncompliant return createdResourceProperties.get("propName"); } public Object getProperty(Resource resource) { - ModifiableValueMap createdResourceProperties = resource.adaptTo(ModifiableValueMap.class); // Noncompliant ValueMap should be used + ModifiableValueMap createdResourceProperties = resource.adaptTo(ModifiableValueMap.class); // Noncompliant return getPropertyFromValueMap("propName", createdResourceProperties); } diff --git a/src/test/files/checks/java/ResourceResolverConsumer.java b/src/test/files/java/ResourceResolverConsumer.java similarity index 97% rename from src/test/files/checks/java/ResourceResolverConsumer.java rename to src/test/files/java/ResourceResolverConsumer.java index 2b399259..9eb074cc 100644 --- a/src/test/files/checks/java/ResourceResolverConsumer.java +++ b/src/test/files/java/ResourceResolverConsumer.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,9 +27,10 @@ import com.day.cq.workflow.WorkflowSession; import com.day.cq.workflow.exec.WorkItem; import com.day.cq.workflow.metadata.MetaDataMap; -import javax.jcr.Session; import org.apache.sling.api.resource.ResourceResolver; +import javax.jcr.Session; + public class ResourceResolverConsumer extends AbstractAssetWorkflowProcess { private final ResourceResolverProducer resourceResolverProducer; diff --git a/src/test/files/checks/java/SampleServlet.java b/src/test/files/java/SampleServlet.java similarity index 94% rename from src/test/files/checks/java/SampleServlet.java rename to src/test/files/java/SampleServlet.java index 1383679b..55ad626e 100644 --- a/src/test/files/checks/java/SampleServlet.java +++ b/src/test/files/java/SampleServlet.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,6 @@ */ package com.example; -import java.io.IOException; -import java.util.Map; -import javax.servlet.ServletException; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.sling.SlingServlet; import org.apache.sling.api.SlingHttpServletRequest; @@ -34,6 +31,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.servlet.ServletException; +import java.io.IOException; +import java.util.Map; + @SlingServlet(paths = "somePath", methods = {HttpConstants.METHOD_GET}) public class SampleServlet extends SlingAllMethodsServlet { @@ -42,34 +43,11 @@ public class SampleServlet extends SlingAllMethodsServlet { @Reference private ResourceResolverFactory resourceResolverFactory; - @Override - protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) - throws ServletException, IOException { - ResourceResolver resourceResolver = null; // Noncompliant {{ResourceResolver should be closed in finally block.}} - try { - resourceResolver = resourceResolverFactory.getServiceResourceResolver(null); - } catch (LoginException e) { - LOGGER.error("Error during getting instance of ResourceResolver class", e); - } finally { - if (resourceResolver != null) { - //resourceResolver.close(); - } - } - } - - @Override - protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) - throws ServletException, IOException { - ResourceResolver resourceResolver = null; - resourceResolver = request.getResourceResolver(); - // do sth - } - /** * Create a new session for specified user (impersonating). */ public static ResourceResolver getResourceResolverForUser(ResourceResolverFactory factory, String userId) - throws LoginException { + throws LoginException { ResourceResolver resolver; if (userId != null) { Map authenticationInfo = new HashMap<>(); @@ -82,24 +60,47 @@ public static ResourceResolver getResourceResolverForUser(ResourceResolverFactor } public static ResourceResolver getResourceResolverForUserNested(ResourceResolverFactory factory, String userId) - throws LoginException { + throws LoginException { ResourceResolver resolver; resolver = getResourceResolverForUser(resourceResolverFactory, userId); return resolver; } public static ResourceResolver getResourceResolverForUserInit(ResourceResolverFactory factory) - throws LoginException { + throws LoginException { ResourceResolver resolver = factory.getServiceResourceResolver(null); return resolver; } public static ResourceResolver getResourceResolverForUserNestedInit(ResourceResolverFactory factory) - throws LoginException { + throws LoginException { ResourceResolver resolver = getResourceResolverForUserInit(resourceResolverFactory); return resolver; } + @Override + protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) + throws ServletException, IOException { + ResourceResolver resourceResolver = null; // Noncompliant {{ResourceResolver should be closed in finally block.}} + try { + resourceResolver = resourceResolverFactory.getServiceResourceResolver(null); + } catch (LoginException e) { + LOGGER.error("Error during getting instance of ResourceResolver class", e); + } finally { + if (resourceResolver != null) { + //resourceResolver.close(); + } + } + } + + @Override + protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) + throws ServletException, IOException { + ResourceResolver resourceResolver = null; + resourceResolver = request.getResourceResolver(); + // do sth + } + public void checkCorrectJumpMethod() { ResourceResolver resourceResolver = null; try { diff --git a/src/test/files/checks/java/SessionLogoutEight.java b/src/test/files/java/SessionLogoutEight.java similarity index 95% rename from src/test/files/checks/java/SessionLogoutEight.java rename to src/test/files/java/SessionLogoutEight.java index 53cd2a38..09cc4a7e 100644 --- a/src/test/files/checks/java/SessionLogoutEight.java +++ b/src/test/files/java/SessionLogoutEight.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,13 @@ */ package com.example; -import javax.jcr.RepositoryException; -import javax.jcr.Session; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.sling.jcr.api.SlingRepository; +import javax.jcr.RepositoryException; +import javax.jcr.Session; + @Component(immediate = true) public class SessionLogout { diff --git a/src/test/files/checks/java/SessionLogoutFive.java b/src/test/files/java/SessionLogoutFive.java similarity index 95% rename from src/test/files/checks/java/SessionLogoutFive.java rename to src/test/files/java/SessionLogoutFive.java index 2fba3ba3..9e2c4b1f 100644 --- a/src/test/files/checks/java/SessionLogoutFive.java +++ b/src/test/files/java/SessionLogoutFive.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,13 @@ */ package com.example; -import javax.jcr.RepositoryException; -import javax.jcr.Session; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.sling.jcr.api.SlingRepository; +import javax.jcr.RepositoryException; +import javax.jcr.Session; + @Component(immediate = true) public class SessionLogout { diff --git a/src/test/files/checks/java/SessionLogoutFour.java b/src/test/files/java/SessionLogoutFour.java similarity index 96% rename from src/test/files/checks/java/SessionLogoutFour.java rename to src/test/files/java/SessionLogoutFour.java index 03b53f92..b7a7f206 100644 --- a/src/test/files/checks/java/SessionLogoutFour.java +++ b/src/test/files/java/SessionLogoutFour.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,13 @@ */ package com.example; -import javax.jcr.RepositoryException; -import javax.jcr.Session; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.sling.jcr.api.SlingRepository; +import javax.jcr.RepositoryException; +import javax.jcr.Session; + @Component(immediate = true) public class SessionLogout { diff --git a/src/test/files/checks/java/SessionLogoutOne.java b/src/test/files/java/SessionLogoutOne.java similarity index 96% rename from src/test/files/checks/java/SessionLogoutOne.java rename to src/test/files/java/SessionLogoutOne.java index cc661303..72798db3 100644 --- a/src/test/files/checks/java/SessionLogoutOne.java +++ b/src/test/files/java/SessionLogoutOne.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,13 @@ */ package com.example; -import javax.jcr.RepositoryException; -import javax.jcr.Session; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.sling.jcr.api.SlingRepository; +import javax.jcr.RepositoryException; +import javax.jcr.Session; + @Component(immediate = true) public class SessionLogout { diff --git a/src/test/files/checks/java/SessionLogoutSeven.java b/src/test/files/java/SessionLogoutSeven.java similarity index 96% rename from src/test/files/checks/java/SessionLogoutSeven.java rename to src/test/files/java/SessionLogoutSeven.java index 5896c209..fa56046e 100644 --- a/src/test/files/checks/java/SessionLogoutSeven.java +++ b/src/test/files/java/SessionLogoutSeven.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,13 @@ */ package com.example; -import javax.jcr.RepositoryException; -import javax.jcr.Session; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.sling.jcr.api.SlingRepository; +import javax.jcr.RepositoryException; +import javax.jcr.Session; + @Component(immediate = true) public class SessionLogout { diff --git a/src/test/files/checks/java/SessionLogoutSix.java b/src/test/files/java/SessionLogoutSix.java similarity index 96% rename from src/test/files/checks/java/SessionLogoutSix.java rename to src/test/files/java/SessionLogoutSix.java index ce7ef077..95ac9484 100644 --- a/src/test/files/checks/java/SessionLogoutSix.java +++ b/src/test/files/java/SessionLogoutSix.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,13 +19,14 @@ */ package com.example; -import javax.jcr.RepositoryException; -import javax.jcr.Session; import org.apache.commons.lang3.StringUtils; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.sling.jcr.api.SlingRepository; +import javax.jcr.RepositoryException; +import javax.jcr.Session; + @Component(immediate = true) public class SessionLogout { diff --git a/src/test/files/checks/java/SessionLogoutThree.java b/src/test/files/java/SessionLogoutThree.java similarity index 95% rename from src/test/files/checks/java/SessionLogoutThree.java rename to src/test/files/java/SessionLogoutThree.java index 8dadd251..6651e92e 100644 --- a/src/test/files/checks/java/SessionLogoutThree.java +++ b/src/test/files/java/SessionLogoutThree.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,13 @@ */ package com.example; -import javax.jcr.RepositoryException; -import javax.jcr.Session; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.sling.jcr.api.SlingRepository; +import javax.jcr.RepositoryException; +import javax.jcr.Session; + @Component(immediate = true) public class SessionLogout { diff --git a/src/test/files/checks/java/SessionLogoutTwo.java b/src/test/files/java/SessionLogoutTwo.java similarity index 95% rename from src/test/files/checks/java/SessionLogoutTwo.java rename to src/test/files/java/SessionLogoutTwo.java index 652cadf2..92133555 100644 --- a/src/test/files/checks/java/SessionLogoutTwo.java +++ b/src/test/files/java/SessionLogoutTwo.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,13 @@ */ package com.example; -import javax.jcr.RepositoryException; -import javax.jcr.Session; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.sling.jcr.api.SlingRepository; +import javax.jcr.RepositoryException; +import javax.jcr.Session; + @Component(immediate = true) public class SessionLogout { diff --git a/src/test/files/checks/slingquery/SlingQueryImplicitStrategyCheck.java b/src/test/files/java/SlingQueryImplicitStrategyCheck.java similarity index 72% rename from src/test/files/checks/slingquery/SlingQueryImplicitStrategyCheck.java rename to src/test/files/java/SlingQueryImplicitStrategyCheck.java index 51f09008..c77b3667 100644 --- a/src/test/files/checks/slingquery/SlingQueryImplicitStrategyCheck.java +++ b/src/test/files/java/SlingQueryImplicitStrategyCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,13 +17,8 @@ * limitations under the License. * #L% */ -package com.cognifide.statistics.accelerator.foundation.datasource; +package com.vml.statistics.accelerator.foundation.datasource; -import static org.apache.sling.query.SlingQuery.$; - -import java.io.IOException; -import java.util.Optional; -import javax.servlet.ServletException; import org.apache.commons.lang3.StringUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; @@ -33,12 +28,18 @@ import org.apache.sling.query.api.SearchStrategy; import org.apache.tools.ant.taskdefs.optional.Script; +import javax.servlet.ServletException; +import java.io.IOException; +import java.util.Optional; + +import static org.apache.sling.query.SlingQuery.$; + public class SlingQueryImplicitStrategyCheck extends SlingAllMethodsServlet { private static final String SOMETHING = "something"; protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { Resource resource = request.getResource(); strategyNotDefined(resource); strategyDefined(resource); @@ -70,7 +71,7 @@ private void strategyDefined(Resource resource) { SlingQuery.$(resource).searchStrategy(SearchStrategy.BFS).find("").find(); $(resource).searchStrategy(SearchStrategy.QUERY).find("res_type").asList().stream() - .map(r -> r.adaptTo(SlingQueryImplicitStrategyCheck.class).toString()).filter(StringUtils::isNotEmpty).iterator(); + .map(r -> r.adaptTo(SlingQueryImplicitStrategyCheck.class).toString()).filter(StringUtils::isNotEmpty).iterator(); } public void casesThatShouldBeIgnored() { @@ -81,33 +82,33 @@ public void casesThatShouldBeIgnored() { } GroupPage groupPage = repository.find(queryModel.getSolrCore(), - queryModel.getPreparedQuery(), - queryModel.getGroupLimit(), - queryModel.getSortType(), - queryModel.getFiltersQueryModel().getFiltersCriteria()); + queryModel.getPreparedQuery(), + queryModel.getGroupLimit(), + queryModel.getSortType(), + queryModel.getFiltersQueryModel().getFiltersCriteria()); } public void testVer1() { this.variable = Optional.of(resource.getResourceMetadata()) - .map(metadata -> metadata.get(ResourceMetadata.RESOLUTION_PATH)) - .filter(String.class::isInstance) - .map(String::valueOf) - .map(path -> resource.getResourceResolver().getResource(path)) - .map(r -> $(r).searchStrategy(SearchStrategy.QUERY).find(SOMETHING).asList()) - .map(list -> list.get(0)); + .map(metadata -> metadata.get(ResourceMetadata.RESOLUTION_PATH)) + .filter(String.class::isInstance) + .map(String::valueOf) + .map(path -> resource.getResourceResolver().getResource(path)) + .map(r -> $(r).searchStrategy(SearchStrategy.QUERY).find(SOMETHING).asList()) + .map(list -> list.get(0)); } public void testVer2() { this.variable = Optional.of(resource.getResourceMetadata()) - .map(metadata -> metadata.get(ResourceMetadata.RESOLUTION_PATH)) - .filter(String.class::isInstance) - .map(String::valueOf) - .map(path -> resource.getResourceResolver().getResource(path)) - .map(r -> $(r).find(SOMETHING).asList()) // Noncompliant - .map(list -> list.get(0)); + .map(metadata -> metadata.get(ResourceMetadata.RESOLUTION_PATH)) + .filter(String.class::isInstance) + .map(String::valueOf) + .map(path -> resource.getResourceResolver().getResource(path)) + .map(r -> $(r).find(SOMETHING).asList()) // Noncompliant + .map(list -> list.get(0)); } private Resource test2() { return resource = Iterables.getFirst($(configurationResource).find(MapConfigurationModel.RESOURCE_TYPE), null); // Noncompliant } -} \ No newline at end of file +} diff --git a/src/test/files/checks/java/slingservlet/SlingServletOne.java b/src/test/files/java/SlingServletOne.java similarity index 82% rename from src/test/files/checks/java/slingservlet/SlingServletOne.java rename to src/test/files/java/SlingServletOne.java index 59a67002..5d07d2cc 100644 --- a/src/test/files/checks/java/slingservlet/SlingServletOne.java +++ b/src/test/files/java/SlingServletOne.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,6 @@ */ package com.example; -import java.io.IOException; -import javax.servlet.ServletException; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; @@ -30,17 +28,20 @@ import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingSafeMethodsServlet; +import javax.servlet.ServletException; +import java.io.IOException; + @Component // Noncompliant {{Prefer cleaner @SlingServlet annotation.}} @Service(value = javax.servlet.Servlet.class) @Properties({@Property(name = "sling.servlet.resourceTypes", value = {"sling/servlet/default"}), - @Property(name = "sling.servlet.selectors", value = {"selector"}), - @Property(name = "sling.servlet.extensions", value = {"tab"}), - @Property(name = "sling.servlet.methods", value = {HttpConstants.METHOD_GET})}) + @Property(name = "sling.servlet.selectors", value = {"selector"}), + @Property(name = "sling.servlet.extensions", value = {"tab"}), + @Property(name = "sling.servlet.methods", value = {HttpConstants.METHOD_GET})}) public class SlingTestOne extends SlingSafeMethodsServlet { @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { //do sth } } diff --git a/src/test/files/checks/java/slingservlet/SlingServletThree.java b/src/test/files/java/SlingServletThree.java similarity index 64% rename from src/test/files/checks/java/slingservlet/SlingServletThree.java rename to src/test/files/java/SlingServletThree.java index b6cafcfa..06bc32ec 100644 --- a/src/test/files/checks/java/slingservlet/SlingServletThree.java +++ b/src/test/files/java/SlingServletThree.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,6 @@ */ package com.example; -import static org.apache.sling.servlets.resolver.internal.ServletResolverConstants.SLING_SERVLET_EXTENSIONS; - -import java.io.IOException; -import javax.servlet.ServletException; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.sling.SlingServlet; @@ -31,19 +27,24 @@ import org.apache.sling.api.servlets.SlingSafeMethodsServlet; import org.apache.sling.servlets.resolver.internal.ServletResolverConstants; +import javax.servlet.ServletException; +import java.io.IOException; + +import static org.apache.sling.servlets.resolver.internal.ServletResolverConstants.SLING_SERVLET_EXTENSIONS; + @SlingServlet(methods = "GET") @Properties({ - @Property(name = Constants.SERVICE_VENDOR, value = "Cognifide"), - @Property(name = Constants.SERVICE_DESCRIPTION, value = "Some description"), - @Property(name = ServletResolverConstants.SLING_SERVLET_SELECTORS, value = "selector"), // Noncompliant {{Property SLING_SERVLET_SELECTORS can be handled by @SlingServlet annotation.}} - @Property(name = SLING_SERVLET_EXTENSIONS, value = "json"), // Noncompliant {{Property SLING_SERVLET_EXTENSIONS can be handled by @SlingServlet annotation.}} - @Property(name = "sling.servlet.resourceTypes", value = {"sling/servlet/default"}) // Noncompliant {{Property "sling.servlet.resourceTypes" can be handled by @SlingServlet annotation.}} + @Property(name = Constants.SERVICE_VENDOR, value = "Cognifide"), + @Property(name = Constants.SERVICE_DESCRIPTION, value = "Some description"), + @Property(name = ServletResolverConstants.SLING_SERVLET_SELECTORS, value = "selector"), // Noncompliant {{Property SLING_SERVLET_SELECTORS can be handled by @SlingServlet annotation.}} + @Property(name = SLING_SERVLET_EXTENSIONS, value = "json"), // Noncompliant {{Property SLING_SERVLET_EXTENSIONS can be handled by @SlingServlet annotation.}} + @Property(name = "sling.servlet.resourceTypes", value = {"sling/servlet/default"}) // Noncompliant {{Property "sling.servlet.resourceTypes" can be handled by @SlingServlet annotation.}} }) public class SlingTestThree extends SlingSafeMethodsServlet { @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { //do sth } } diff --git a/src/test/files/checks/java/slingservlet/SlingServletTwo.java b/src/test/files/java/SlingServletTwo.java similarity index 85% rename from src/test/files/checks/java/slingservlet/SlingServletTwo.java rename to src/test/files/java/SlingServletTwo.java index 8eae2661..20844279 100644 --- a/src/test/files/checks/java/slingservlet/SlingServletTwo.java +++ b/src/test/files/java/SlingServletTwo.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,6 @@ */ package com.example; -import java.io.IOException; -import javax.servlet.ServletException; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Service; @@ -29,16 +27,19 @@ import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.SlingSafeMethodsServlet; +import javax.servlet.ServletException; +import java.io.IOException; + @Service // Noncompliant {{@Component nor @Service annotation is not needed when @SlingServlet is used.}} @SlingServlet(resourceTypes = "sling/servlet/default", selectors = "someSelector", extensions = "json", methods = "GET") @Properties({ - @Property(name = Constants.SERVICE_VENDOR, value = "Cognifide"), - @Property(name = Constants.SERVICE_DESCRIPTION, value = "Some description")}) + @Property(name = Constants.SERVICE_VENDOR, value = "Cognifide"), + @Property(name = Constants.SERVICE_DESCRIPTION, value = "Some description")}) public class SlingTestTwo extends SlingSafeMethodsServlet { @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { //do sth } } diff --git a/src/test/files/checks/java/slingservlet/SlingServletWithStandardAnnotations.java b/src/test/files/java/SlingServletWithStandardAnnotations.java similarity index 81% rename from src/test/files/checks/java/slingservlet/SlingServletWithStandardAnnotations.java rename to src/test/files/java/SlingServletWithStandardAnnotations.java index 6f227fa3..0f10d3ab 100644 --- a/src/test/files/checks/java/slingservlet/SlingServletWithStandardAnnotations.java +++ b/src/test/files/java/SlingServletWithStandardAnnotations.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,26 +19,27 @@ */ package com.example; -import java.io.IOException; -import javax.servlet.Servlet; -import javax.servlet.ServletException; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingSafeMethodsServlet; import org.osgi.service.component.annotations.Component; +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import java.io.IOException; + @Component(property = { // Compliant {{ OSGi standard annotations are OK}} - "sling.servlet.resourceTypes=sling/servlet/default", - "sling.servlet.selectors=selector", - "sling.servlet.extensions=tab", - "sling.servlet.methods=" + HttpConstants.METHOD_GET + "sling.servlet.resourceTypes=sling/servlet/default", + "sling.servlet.selectors=selector", + "sling.servlet.extensions=tab", + "sling.servlet.methods=" + HttpConstants.METHOD_GET }, service = Servlet.class) public class SlingServletWithStandardAnnotations extends SlingSafeMethodsServlet { @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { //do sth } } diff --git a/src/test/files/checks/java/SynchronizedKeywordUsageCheck.java b/src/test/files/java/SynchronizedKeywordUsageCheck.java similarity index 96% rename from src/test/files/checks/java/SynchronizedKeywordUsageCheck.java rename to src/test/files/java/SynchronizedKeywordUsageCheck.java index ab800086..a3ba0397 100644 --- a/src/test/files/checks/java/SynchronizedKeywordUsageCheck.java +++ b/src/test/files/java/SynchronizedKeywordUsageCheck.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ public class SynchronizedKeywordUsageCheck { private final List list = new ArrayList<>(16); + private int counter = 0; public synchronized void addElement(String s) { // Noncompliant {{Usage of 'synchronized' keyword should be avoided if possible.}} list.add(s); @@ -36,8 +37,6 @@ public void removeElement(String s) { } } - private int counter = 0; - public synchronized void increment() { // Noncompliant counter++; } diff --git a/src/test/files/checks/java/ThreadSafeFieldCheckDsComponentAnnotation.java b/src/test/files/java/ThreadSafeFieldCheckDsComponentAnnotation.java similarity index 94% rename from src/test/files/checks/java/ThreadSafeFieldCheckDsComponentAnnotation.java rename to src/test/files/java/ThreadSafeFieldCheckDsComponentAnnotation.java index 8628b041..898d280a 100644 --- a/src/test/files/checks/java/ThreadSafeFieldCheckDsComponentAnnotation.java +++ b/src/test/files/java/ThreadSafeFieldCheckDsComponentAnnotation.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,10 @@ */ package com.example; -import javax.jcr.Session; import org.osgi.service.component.annotations.Component; +import javax.jcr.Session; + @Component public class ThreadSafeFieldCheckDsComponentAnnotationExample { diff --git a/src/test/files/checks/java/ThreadSafeFieldCheckEventHandler.java b/src/test/files/java/ThreadSafeFieldCheckEventHandler.java similarity index 94% rename from src/test/files/checks/java/ThreadSafeFieldCheckEventHandler.java rename to src/test/files/java/ThreadSafeFieldCheckEventHandler.java index 470827a9..20568033 100644 --- a/src/test/files/checks/java/ThreadSafeFieldCheckEventHandler.java +++ b/src/test/files/java/ThreadSafeFieldCheckEventHandler.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,10 @@ */ package com.example; -import javax.jcr.Session; import org.osgi.service.event.EventHandler; +import javax.jcr.Session; + public class ThreadSafeFieldCheckEventHandlerExample implements EventHandler { diff --git a/src/test/files/checks/java/ThreadSafeFieldCheckFilter.java b/src/test/files/java/ThreadSafeFieldCheckFilter.java similarity index 92% rename from src/test/files/checks/java/ThreadSafeFieldCheckFilter.java rename to src/test/files/java/ThreadSafeFieldCheckFilter.java index 28d65824..75ebf878 100644 --- a/src/test/files/checks/java/ThreadSafeFieldCheckFilter.java +++ b/src/test/files/java/ThreadSafeFieldCheckFilter.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,18 +21,19 @@ import com.day.cq.tagging.TagManager; import com.day.cq.wcm.api.PageManager; -import java.io.IOException; +import org.apache.felix.scr.annotations.sling.SlingFilter; +import org.apache.felix.scr.annotations.sling.SlingFilterScope; + import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; -import org.apache.felix.scr.annotations.sling.SlingFilter; -import org.apache.felix.scr.annotations.sling.SlingFilterScope; +import java.io.IOException; @SlingFilter(scope = SlingFilterScope.COMPONENT, order = Integer.MAX_VALUE, metatype = true, label = - "label", description = "description") + "label", description = "description") public class ThreadSafeFieldCheckFilterExample implements Filter { private PageManager pageManager; // Noncompliant {{Usage of com.day.cq.wcm.api.PageManager as a field is not thread safe.}} @@ -46,7 +47,7 @@ public void init(FilterConfig filterConfig) throws ServletException { @Override public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) - throws IOException, ServletException { + throws IOException, ServletException { // filter } diff --git a/src/test/files/checks/java/ThreadSafeFieldCheckScrComponentAnnotation.java b/src/test/files/java/ThreadSafeFieldCheckScrComponentAnnotation.java similarity index 93% rename from src/test/files/checks/java/ThreadSafeFieldCheckScrComponentAnnotation.java rename to src/test/files/java/ThreadSafeFieldCheckScrComponentAnnotation.java index 010d152e..ae9a508a 100644 --- a/src/test/files/checks/java/ThreadSafeFieldCheckScrComponentAnnotation.java +++ b/src/test/files/java/ThreadSafeFieldCheckScrComponentAnnotation.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,10 @@ */ package com.example; -import javax.jcr.Session; import org.apache.felix.scr.annotations.Component; +import javax.jcr.Session; + @Component public class ThreadSafeFieldCheckComponentAnnotationExample { diff --git a/src/test/files/checks/java/ThreadSafeFieldCheckServlet.java b/src/test/files/java/ThreadSafeFieldCheckServlet.java similarity index 97% rename from src/test/files/checks/java/ThreadSafeFieldCheckServlet.java rename to src/test/files/java/ThreadSafeFieldCheckServlet.java index 2b2298af..f266bf23 100644 --- a/src/test/files/checks/java/ThreadSafeFieldCheckServlet.java +++ b/src/test/files/java/ThreadSafeFieldCheckServlet.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/files/checks/java/ThreadSafeFieldCheckSlingServletAnnotation.java b/src/test/files/java/ThreadSafeFieldCheckSlingServletAnnotation.java similarity index 93% rename from src/test/files/checks/java/ThreadSafeFieldCheckSlingServletAnnotation.java rename to src/test/files/java/ThreadSafeFieldCheckSlingServletAnnotation.java index b945ca24..a670b840 100644 --- a/src/test/files/checks/java/ThreadSafeFieldCheckSlingServletAnnotation.java +++ b/src/test/files/java/ThreadSafeFieldCheckSlingServletAnnotation.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,10 @@ */ package com.example; -import javax.jcr.Session; import org.apache.felix.scr.annotations.sling.SlingServlet; +import javax.jcr.Session; + @SlingServlet public class ThreadSafeFieldCheckSlingServletExample { diff --git a/src/test/java/com/cognifide/aemrules/extensions/RulesLoaderTest.java b/src/test/java/com/cognifide/aemrules/extensions/RulesLoaderTest.java deleted file mode 100644 index 7c1db604..00000000 --- a/src/test/java/com/cognifide/aemrules/extensions/RulesLoaderTest.java +++ /dev/null @@ -1,336 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.extensions; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; - -import com.cognifide.aemrules.java.rules.JavaCheckClasses; -import com.cognifide.aemrules.metadata.Metadata; -import com.cognifide.aemrules.tag.Tags; -import com.cognifide.aemrules.version.AemVersion; - -import java.util.Arrays; -import java.util.List; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.api.server.rule.RulesDefinition.NewRepository; -import org.sonar.check.Priority; -import org.sonar.check.Rule; -import org.sonar.check.RuleProperty; -import org.sonar.plugins.java.api.JavaCheck; -import org.sonar.plugins.java.api.JavaFileScanner; -import org.sonar.plugins.java.api.JavaFileScannerContext; -import org.sonar.plugins.java.api.tree.BaseTreeVisitor; - -public class RulesLoaderTest { - - private static final String RULE_KEY = "AEM-TEST"; - - private static final String RULE_NAME = "test"; - - private static final String TECHNICAL_DEBT = "10min"; - - private static final String RULE_MARKDOWN_TEST_DESCRIPTION = "Test description."; - - private static final String RULE_PROPERTY_KEY = "testKey"; - - private static final String RULE_PROPERTY_DESCRIPTION = "testDescription"; - - private static final String RULES_PROPERTY_DEFAULT_VALUE = "testDefault"; - - private static final String RULES_PROPERTY_TYPE = "testType"; - - private NewRepository repo; - - private RulesDefinition.Context context; - - @Before - public void setUp() { - context = new RulesDefinition.Context(); - repo = context.createRepository(JavaCheckClasses.REPOSITORY_KEY, "java"); - repo.setName(JavaCheckClasses.REPOSITORY_KEY); - } - - @Test - public void shouldLoadRuleWithAllSettings() { - givenRulesLoaded(Arrays.asList(RuleWithAllSettings.class)); - - RulesDefinition.Repository repository = context.repository(JavaCheckClasses.REPOSITORY_KEY); - RulesDefinition.Rule rule = repository.rule(RULE_KEY); - - Assert.assertThat(rule.markdownDescription(), is(RULE_MARKDOWN_TEST_DESCRIPTION)); - Assert.assertThat(rule.name(), is(RULE_NAME)); - Assert.assertThat(rule.severity(), is(Priority.MINOR.toString())); - Assert.assertThat(rule.tags().contains(Tags.AEM), is(true)); - Assert.assertThat(rule.debtRemediationFunction().baseEffort(), is(TECHNICAL_DEBT)); - } - - @Test - public void shouldNotSetTechnicalDebtWhenAnnotationNotPresent() { - givenRulesLoaded(Arrays.asList(RuleWithoutMetadataAnnotation.class)); - - RulesDefinition.Repository repository = context.repository(JavaCheckClasses.REPOSITORY_KEY); - RulesDefinition.Rule rule = repository.rule(RULE_KEY); - - Assert.assertThat(rule.markdownDescription(), is(RULE_MARKDOWN_TEST_DESCRIPTION)); - Assert.assertThat(rule.name(), is(RULE_NAME)); - Assert.assertThat(rule.severity(), is(Priority.MINOR.toString())); - Assert.assertThat(rule.tags().contains(Tags.AEM), is(true)); - Assert.assertThat(rule.debtRemediationFunction(), is(nullValue())); - } - - @Test - public void shouldNotSetTechnicalDebtWhenTechnicalDebtNotSetInMetadata() { - givenRulesLoaded(Arrays.asList(RuleWithEmptyTechnicalDebt.class)); - - RulesDefinition.Repository repository = context.repository(JavaCheckClasses.REPOSITORY_KEY); - RulesDefinition.Rule rule = repository.rule(RULE_KEY); - - Assert.assertThat(rule.markdownDescription(), is(RULE_MARKDOWN_TEST_DESCRIPTION)); - Assert.assertThat(rule.name(), is(RULE_NAME)); - Assert.assertThat(rule.severity(), is(Priority.MINOR.toString())); - Assert.assertThat(rule.tags().contains(Tags.AEM), is(true)); - Assert.assertThat(rule.debtRemediationFunction(), is(nullValue())); - } - - @Test - public void shouldNotLoadRuleWhenRuleAnnotationIsNotPresent() { - givenRulesLoaded(Arrays.asList(RuleWithoutRuleAnnotation.class)); - - RulesDefinition.Repository repository = context.repository(JavaCheckClasses.REPOSITORY_KEY); - RulesDefinition.Rule rule = repository.rule(RULE_KEY); - - Assert.assertThat(rule, is(nullValue())); - } - - - @Test - public void shouldSetDefaultValuesWhenRuleAttributeWithNameOnly() { - givenRulesLoaded(Arrays.asList(RuleWithOnlyNameAttribute.class)); - - RulesDefinition.Repository repository = context.repository(JavaCheckClasses.REPOSITORY_KEY); - RulesDefinition.Rule rule = repository.rule("com.cognifide.aemrules.extensions.RulesLoaderTest.RuleWithOnlyNameAttribute"); - - Assert.assertThat(rule.markdownDescription(), is("No description yet.")); - Assert.assertThat(rule.name(), is(RULE_NAME)); - Assert.assertThat(rule.severity(), is(Priority.MAJOR.toString())); - Assert.assertThat(rule.tags().size(), is(0)); - Assert.assertThat(rule.debtRemediationFunction().baseEffort(), is(TECHNICAL_DEBT)); - } - - @Test(expected = IllegalStateException.class) - public void shouldThrowExceptionWhenRuleNameNotProvide() { - givenRulesLoaded(Arrays.asList(RuleWithoutNameAttributeSet.class)); - } - - @Test - public void shouldLoadRuleWithProperty() { - givenRulesLoaded(Arrays.asList(RuleWithRuleProperty.class)); - - RulesDefinition.Repository repository = context.repository(JavaCheckClasses.REPOSITORY_KEY); - RulesDefinition.Rule rule = repository.rule(RULE_KEY); - RulesDefinition.Param param = rule.param(RULE_PROPERTY_KEY); - - Assert.assertThat(param.description(), is(RULE_PROPERTY_DESCRIPTION)); - Assert.assertThat(param.defaultValue(), is(RULES_PROPERTY_DEFAULT_VALUE)); - Assert.assertThat(param.type().type(), is(RULES_PROPERTY_TYPE)); - } - - @Test - public void shouldLoadRuleWithPropertyWithoutAttributes() { - givenRulesLoaded(Arrays.asList(RuleWithRulePropertyWithoutAttributes.class)); - - RulesDefinition.Repository repository = context.repository(JavaCheckClasses.REPOSITORY_KEY); - RulesDefinition.Rule rule = repository.rule(RULE_KEY); - RulesDefinition.Param param = rule.param("testProperty"); - - Assert.assertThat(param.description(), is(nullValue())); - Assert.assertThat(param.defaultValue(), is(nullValue())); - Assert.assertThat(param.type().type(), is("STRING")); - } - - private void givenRulesLoaded(List> annotationClasses) { - RulesLoader rulesLoader = new RulesLoader(); - rulesLoader.load(repo, annotationClasses); - repo.done(); - } - - @Rule( - key = RULE_KEY, - name = RULE_NAME, - priority = Priority.MINOR, - tags = Tags.AEM - ) - @AemVersion( - all = true - ) - @Metadata( - technicalDebt = TECHNICAL_DEBT - ) - private class RuleWithAllSettings extends BaseTreeVisitor implements JavaFileScanner { - - @Override - public void scanFile(JavaFileScannerContext javaFileScannerContext) { - - } - } - - @Rule( - key = RULE_KEY, - name = RULE_NAME, - priority = Priority.MINOR, - tags = Tags.AEM - ) - @AemVersion( - all = true - ) - private class RuleWithoutMetadataAnnotation extends BaseTreeVisitor implements JavaFileScanner { - - @Override - public void scanFile(JavaFileScannerContext javaFileScannerContext) { - - } - } - - @Rule( - key = RULE_KEY, - name = RULE_NAME, - priority = Priority.MINOR, - tags = Tags.AEM - ) - @AemVersion( - all = true - ) - @Metadata( - technicalDebt = "" - ) - private class RuleWithEmptyTechnicalDebt extends BaseTreeVisitor implements JavaFileScanner { - - @Override - public void scanFile(JavaFileScannerContext javaFileScannerContext) { - - } - } - - @AemVersion( - all = true - ) - @Metadata( - technicalDebt = TECHNICAL_DEBT - ) - private class RuleWithoutRuleAnnotation extends BaseTreeVisitor implements JavaFileScanner { - - @Override - public void scanFile(JavaFileScannerContext javaFileScannerContext) { - - } - } - - @Rule( - name = RULE_NAME - ) - @AemVersion( - all = true - ) - @Metadata( - technicalDebt = TECHNICAL_DEBT - ) - private class RuleWithOnlyNameAttribute extends BaseTreeVisitor implements JavaFileScanner { - - @Override - public void scanFile(JavaFileScannerContext javaFileScannerContext) { - - } - } - - @Rule( - key = RULE_KEY, - priority = Priority.MINOR, - tags = Tags.AEM - ) - @AemVersion( - all = true - ) - @Metadata( - technicalDebt = TECHNICAL_DEBT - ) - private class RuleWithoutNameAttributeSet extends BaseTreeVisitor implements JavaFileScanner { - - @Override - public void scanFile(JavaFileScannerContext javaFileScannerContext) { - - } - } - - @Rule( - key = RULE_KEY, - name = RULE_NAME, - priority = Priority.MINOR, - tags = Tags.AEM - ) - @AemVersion( - all = true - ) - @Metadata( - technicalDebt = TECHNICAL_DEBT - ) - private class RuleWithRuleProperty extends BaseTreeVisitor implements JavaFileScanner { - - @RuleProperty( - key = RULE_PROPERTY_KEY, - description = RULE_PROPERTY_DESCRIPTION, - defaultValue = RULES_PROPERTY_DEFAULT_VALUE, - type = RULES_PROPERTY_TYPE - ) - private String testProperty; - - @Override - public void scanFile(JavaFileScannerContext javaFileScannerContext) { - - } - } - - @Rule( - key = RULE_KEY, - name = RULE_NAME, - priority = Priority.MINOR, - tags = Tags.AEM - ) - @AemVersion( - all = true - ) - @Metadata( - technicalDebt = TECHNICAL_DEBT - ) - private class RuleWithRulePropertyWithoutAttributes extends BaseTreeVisitor implements JavaFileScanner { - - @RuleProperty - private String testProperty; - - @Override - public void scanFile(JavaFileScannerContext javaFileScannerContext) { - - } - } - -} diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/AvoidUsingUnsafeDisplayContextCheckTest.java b/src/test/java/com/cognifide/aemrules/htl/checks/AvoidUsingUnsafeDisplayContextCheckTest.java deleted file mode 100644 index f216d3bf..00000000 --- a/src/test/java/com/cognifide/aemrules/htl/checks/AvoidUsingUnsafeDisplayContextCheckTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; - -public class AvoidUsingUnsafeDisplayContextCheckTest extends AbstractBaseTest { - - @Test - public void checkAllDataAttributesContainsDisplayContext() { - check = new AvoidUsingUnsafeDisplayContextCheck(); - filename = "src/test/files/checks/htl/AvoidUsingUnsafeDisplayContextCheck.html"; - verify(); - } -} \ No newline at end of file diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/DisplayContextIsMandatoryForInlineStylesCheckTest.java b/src/test/java/com/cognifide/aemrules/htl/checks/DisplayContextIsMandatoryForInlineStylesCheckTest.java deleted file mode 100644 index 74785993..00000000 --- a/src/test/java/com/cognifide/aemrules/htl/checks/DisplayContextIsMandatoryForInlineStylesCheckTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; - -public class DisplayContextIsMandatoryForInlineStylesCheckTest extends AbstractBaseTest { - - @Test - public void checkInlineStyleDisplayContext() { - check = new InlineStyleMandatoryDisplayContextCheck(); - filename = "src/test/files/checks/htl/DefineDisplayContextInInlineStylesCheck.html"; - verify(); - } -} diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/DisplayContextIsMandatoryInEventAttributesTest.java b/src/test/java/com/cognifide/aemrules/htl/checks/DisplayContextIsMandatoryInEventAttributesTest.java deleted file mode 100644 index baa923ce..00000000 --- a/src/test/java/com/cognifide/aemrules/htl/checks/DisplayContextIsMandatoryInEventAttributesTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; - -public class DisplayContextIsMandatoryInEventAttributesTest extends AbstractBaseTest { - - @Test - public void checkEventAttributeDisplayContext() { - check = new EventMandatoryDisplayContextCheck(); - filename = "src/test/files/checks/htl/DefineDisplayContextInEventAttributes.html"; - verify(); - } -} diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/DisplayContextIsMandatoryInScriptsAndStylesCheckTest.java b/src/test/java/com/cognifide/aemrules/htl/checks/DisplayContextIsMandatoryInScriptsAndStylesCheckTest.java deleted file mode 100644 index 42cd0b35..00000000 --- a/src/test/java/com/cognifide/aemrules/htl/checks/DisplayContextIsMandatoryInScriptsAndStylesCheckTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; - -public class DisplayContextIsMandatoryInScriptsAndStylesCheckTest extends AbstractBaseTest { - - @Test - public void checkScriptsAndStyleDisplayContext() { - check = new ScriptsAndStyleMandatoryDisplayContextCheck(); - filename = "src/test/files/checks/htl/DefineDisplayContextInScriptsAndStylesCheck.html"; - verify(); - } -} diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/ExplicitNamesInLoopsCheckTest.java b/src/test/java/com/cognifide/aemrules/htl/checks/ExplicitNamesInLoopsCheckTest.java deleted file mode 100644 index 2b457dfa..00000000 --- a/src/test/java/com/cognifide/aemrules/htl/checks/ExplicitNamesInLoopsCheckTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; - -public class ExplicitNamesInLoopsCheckTest extends AbstractBaseTest { - - @Test - public void ExplicitNamesInLoopsCheck() { - check = new ExplicitNamesInLoopsCheck(); - filename = "src/test/files/checks/htl/ExplicitNamesInLoopsCheck.html"; - verify(); - } -} \ No newline at end of file diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/HtlAttributesShouldBeAtTheEndCheckTest.java b/src/test/java/com/cognifide/aemrules/htl/checks/HtlAttributesShouldBeAtTheEndCheckTest.java deleted file mode 100644 index ab26cd7b..00000000 --- a/src/test/java/com/cognifide/aemrules/htl/checks/HtlAttributesShouldBeAtTheEndCheckTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; - -public class HtlAttributesShouldBeAtTheEndCheckTest extends AbstractBaseTest { - - @Test - public void checkHtlAttributesOrder() { - check = new HtlAttributesShouldBeAtTheEndCheck(); - filename = "src/test/files/checks/htl/HtlAttributesShouldBeAtTheEndCheck.html"; - verify(); - } -} \ No newline at end of file diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/HtlCommentsCheckTest.java b/src/test/java/com/cognifide/aemrules/htl/checks/HtlCommentsCheckTest.java deleted file mode 100644 index c54b8923..00000000 --- a/src/test/java/com/cognifide/aemrules/htl/checks/HtlCommentsCheckTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ - -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; - -public class HtlCommentsCheckTest extends AbstractBaseTest { - - @Test - public void checkHTLStyleOfCommenting() { - check = new HtlCommentsCheck(); - filename = "src/test/files/checks/htl/HtlCommentsCheck.html"; - verify(); - } -} \ No newline at end of file diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/NamingAndReusingConditionsCheckTest.java b/src/test/java/com/cognifide/aemrules/htl/checks/NamingAndReusingConditionsCheckTest.java deleted file mode 100644 index 3cc1e444..00000000 --- a/src/test/java/com/cognifide/aemrules/htl/checks/NamingAndReusingConditionsCheckTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; - -public class NamingAndReusingConditionsCheckTest extends AbstractBaseTest { - - @Test - public void checkHtlAttributesOrder() { - check = new NamingAndReusingConditionsCheck(); - filename = "src/test/files/checks/htl/NamingAndReusingConditionsCheck.html"; - verify(); - } -} \ No newline at end of file diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/PlaceTemplatesInSeparateFilesCheckTest.java b/src/test/java/com/cognifide/aemrules/htl/checks/PlaceTemplatesInSeparateFilesCheckTest.java deleted file mode 100644 index 6fb90fcf..00000000 --- a/src/test/java/com/cognifide/aemrules/htl/checks/PlaceTemplatesInSeparateFilesCheckTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; - -public class PlaceTemplatesInSeparateFilesCheckTest extends AbstractBaseTest { - - @Test - public void checkHtlAttributesOrder() { - check = new PlaceTemplatesInSeparateFilesCheck(); - filename = "src/test/files/checks/htl/PlaceTemplatesInSeparateFilesCheck.html"; - verify(); - } -} \ No newline at end of file diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/UseMostRestrictiveHtlContextCheckTest.java b/src/test/java/com/cognifide/aemrules/htl/checks/UseMostRestrictiveHtlContextCheckTest.java deleted file mode 100644 index 283dc890..00000000 --- a/src/test/java/com/cognifide/aemrules/htl/checks/UseMostRestrictiveHtlContextCheckTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.htl.checks; - -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; - -public class UseMostRestrictiveHtlContextCheckTest extends AbstractBaseTest { - - @Test - public void checkAllDataAttributesContainsDisplayContext() { - check = new UseMostRestrictiveHtlContextCheck(); - filename = "src/test/files/checks/htl/UseMostRestrictiveHtlContextCheck.html"; - verify(); - } -} \ No newline at end of file diff --git a/src/test/java/com/cognifide/aemrules/java/checks/ContentResourceShouldBeNullCheckedCheckTest.java b/src/test/java/com/cognifide/aemrules/java/checks/ContentResourceShouldBeNullCheckedCheckTest.java deleted file mode 100644 index 48416ff0..00000000 --- a/src/test/java/com/cognifide/aemrules/java/checks/ContentResourceShouldBeNullCheckedCheckTest.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.java.checks; - -import org.junit.Test; - -public class ContentResourceShouldBeNullCheckedCheckTest extends AbstractBaseTest { - - @Test - public void checkIfContentResourceIsNotNull() { - check = new ContentResourceShouldBeNullCheckedCheck(); - filename = "src/test/files/checks/java/ContentResourceShouldBeNullCheckedCheck.java"; - verify(); - } -} diff --git a/src/test/java/com/cognifide/aemrules/java/checks/DefaultInjectionStrategyAnnotationCheckTest.java b/src/test/java/com/cognifide/aemrules/java/checks/DefaultInjectionStrategyAnnotationCheckTest.java deleted file mode 100644 index af66fc05..00000000 --- a/src/test/java/com/cognifide/aemrules/java/checks/DefaultInjectionStrategyAnnotationCheckTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.java.checks; - -import com.cognifide.aemrules.java.checks.slingmodels.DefaultInjectionStrategyAnnotationCheck; -import org.junit.Test; - -public class DefaultInjectionStrategyAnnotationCheckTest extends AbstractBaseTest { - - @Test - public void checkAnnotation() { - check = new DefaultInjectionStrategyAnnotationCheck(); - filename = "src/test/files/checks/java/slingmodels/DefaultInjectionStrategyAnnotationCheck.java"; - verify(); - } - - @Test - public void checkMultipleAdaptablesAnnotation() { - check = new DefaultInjectionStrategyAnnotationCheck(); - filename = "src/test/files/checks/java/slingmodels/DefaultInjectionStrategyAnnotationCheckMultipleAdaptables.java"; - verify(); - } - -} diff --git a/src/test/java/com/cognifide/aemrules/java/checks/PreferSlingServletAnnotationTest.java b/src/test/java/com/cognifide/aemrules/java/checks/PreferSlingServletAnnotationTest.java deleted file mode 100644 index b0fdcb95..00000000 --- a/src/test/java/com/cognifide/aemrules/java/checks/PreferSlingServletAnnotationTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.java.checks; - -import org.junit.Test; - -public class PreferSlingServletAnnotationTest extends AbstractBaseTest { - - @Test - public void checkLackOfAnnotation() { - check = new PreferSlingServletAnnotation(); - filename = "src/test/files/checks/java/slingservlet/SlingServletOne.java"; - verify(); - } - - @Test - public void checkMixedAnnotations() { - check = new PreferSlingServletAnnotation(); - filename = "src/test/files/checks/java/slingservlet/SlingServletTwo.java"; - verify(); - } - - @Test - public void checkRedundantProperties() { - check = new PreferSlingServletAnnotation(); - filename = "src/test/files/checks/java/slingservlet/SlingServletThree.java"; - verify(); - } - - @Test - public void checkStandardAnnotations() { - check = new PreferSlingServletAnnotation(); - filename = "src/test/files/checks/java/slingservlet/SlingServletWithStandardAnnotations.java"; - verifyNoIssues(); - } -} diff --git a/src/test/java/com/cognifide/aemrules/java/checks/ResourceResolverShouldBeClosedTest.java b/src/test/java/com/cognifide/aemrules/java/checks/ResourceResolverShouldBeClosedTest.java deleted file mode 100644 index 171ddf94..00000000 --- a/src/test/java/com/cognifide/aemrules/java/checks/ResourceResolverShouldBeClosedTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.java.checks; - -import org.junit.Test; - -import com.cognifide.aemrules.java.checks.resourceresolver.close.ResourceResolverShouldBeClosed; - -public class ResourceResolverShouldBeClosedTest extends AbstractBaseTest { - - @Test - public void checkInjectorNotClosedInFinallyBlock() { - check = new ResourceResolverShouldBeClosed(); - filename = "src/test/files/checks/java/SampleServlet.java"; - verify(); - } - - @Test - public void checkResourceResolverNotClosedInFinallyBlockWhenResourceResolverComesFromDifferentClass() { - check = new ResourceResolverShouldBeClosed(); - filename = "src/test/files/checks/java/ResourceResolverConsumer.java"; - verifyNoIssues(); - } - - @Test - public void checkResourceResolverNotClosedWhenItIsOpenedInActivateAndClosedInDeactivate() { - check = new ResourceResolverShouldBeClosed(); - filename = "src/test/files/checks/java/LongSessionService.java"; - verifyNoIssues(); - } - - @Test - public void checkResourceResolverClosedInDeactivateMethod() { - check = new ResourceResolverShouldBeClosed(); - filename = "src/test/files/checks/java/LongSessionEventListener.java"; - verifyNoIssues(); - } - - @Test - public void checkResourceResolverClosedInDeactivateMethodError() { - check = new ResourceResolverShouldBeClosed(); - filename = "src/test/files/checks/java/LongResourceResolverEvenListenerError.java"; - verify(); - } - -} diff --git a/src/test/java/com/cognifide/aemrules/java/checks/ResourceResolverTryWithResourcesTest.java b/src/test/java/com/cognifide/aemrules/java/checks/ResourceResolverTryWithResourcesTest.java deleted file mode 100644 index 57e9d722..00000000 --- a/src/test/java/com/cognifide/aemrules/java/checks/ResourceResolverTryWithResourcesTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.java.checks; - -import com.cognifide.aemrules.java.checks.resourceresolver.close.ResourceResolverTryWithResourcesCheck; -import org.junit.Test; - -public class ResourceResolverTryWithResourcesTest extends AbstractBaseTest { - - @Test - public void checkResourceResolverUsesTryWithResourcesBlock() { - check = new ResourceResolverTryWithResourcesCheck(); - filename = "src/test/files/checks/java/resourceresolver/AutoclosableResourceResolver.java"; - verify(); - } - -} \ No newline at end of file diff --git a/src/test/java/com/cognifide/aemrules/java/checks/SessionShouldBeLoggedOutTest.java b/src/test/java/com/cognifide/aemrules/java/checks/SessionShouldBeLoggedOutTest.java deleted file mode 100644 index 68350c12..00000000 --- a/src/test/java/com/cognifide/aemrules/java/checks/SessionShouldBeLoggedOutTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.java.checks; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(Parameterized.class) -public class SessionShouldBeLoggedOutTest extends AbstractBaseTest { - - // format is filename, failure expected - @Parameterized.Parameters - public static Collection data() { - return Arrays.asList(new Object[][]{ - {"src/test/files/checks/java/SessionLogoutOne.java", false}, - {"src/test/files/checks/java/SessionLogoutTwo.java", false}, - {"src/test/files/checks/java/SessionLogoutThree.java", false}, - {"src/test/files/checks/java/SessionLogoutFour.java", true}, - {"src/test/files/checks/java/SessionLogoutFive.java", true}, - {"src/test/files/checks/java/SessionLogoutSix.java", true}, - {"src/test/files/checks/java/SessionLogoutSeven.java", true}, - {"src/test/files/checks/java/SessionLogoutEight.java", false}, - {"src/test/files/checks/java/LongSessionEventListener.java", false}, - {"src/test/files/checks/java/LongSessionEventListenerError.java", true} - }); - } - - private boolean expectFailure; - - public SessionShouldBeLoggedOutTest(Object fn, Object expectFailure) { - filename = (String) fn; - this.expectFailure = ((Boolean) expectFailure).booleanValue(); - } - - @Test - public void checkInjectorNotClosedInFinallyBlock() { - check = new SessionShouldBeLoggedOut(); - if (expectFailure) { - verify(); - } else { - verifyNoIssues(); - } - } - -} diff --git a/src/test/java/com/cognifide/aemrules/java/checks/SlingQueryImplicitStrategyCheckTest.java b/src/test/java/com/cognifide/aemrules/java/checks/SlingQueryImplicitStrategyCheckTest.java deleted file mode 100644 index 0cd0c3c2..00000000 --- a/src/test/java/com/cognifide/aemrules/java/checks/SlingQueryImplicitStrategyCheckTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.java.checks; - -import com.cognifide.aemrules.java.checks.slingquery.SlingQueryImplicitStrategyCheck; -import org.junit.Test; - -public class SlingQueryImplicitStrategyCheckTest extends AbstractBaseTest { - - @Test - public void checkImplicitSearches() { - check = new SlingQueryImplicitStrategyCheck(); - filename = "src/test/files/checks/slingquery/SlingQueryImplicitStrategyCheck.java"; - verify(); - } - -} diff --git a/src/test/java/com/cognifide/aemrules/java/checks/ThreadSafeFieldCheckTest.java b/src/test/java/com/cognifide/aemrules/java/checks/ThreadSafeFieldCheckTest.java deleted file mode 100644 index a95c23b8..00000000 --- a/src/test/java/com/cognifide/aemrules/java/checks/ThreadSafeFieldCheckTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.java.checks; - -import org.junit.Test; - -public class ThreadSafeFieldCheckTest extends AbstractBaseTest { - - @Test - public void checkThreadSafeFieldsInServlet() { - check = new ThreadSafeFieldCheck(); - filename = "src/test/files/checks/java/ThreadSafeFieldCheckServlet.java"; - verify(); - } - - @Test - public void checkThreadSafeFieldsInFilter() { - check = new ThreadSafeFieldCheck(); - filename = "src/test/files/checks/java/ThreadSafeFieldCheckFilter.java"; - verify(); - } - - @Test - public void checkThreadSafeFieldsInEventHandler() { - check = new ThreadSafeFieldCheck(); - filename = "src/test/files/checks/java/ThreadSafeFieldCheckEventHandler.java"; - verify(); - } - - @Test - public void checkThreadSafeFieldsInScrComponent() { - check = new ThreadSafeFieldCheck(); - filename = "src/test/files/checks/java/ThreadSafeFieldCheckScrComponentAnnotation.java"; - verify(); - } - - @Test - public void checkThreadSafeFieldsInDsComponent() { - check = new ThreadSafeFieldCheck(); - filename = "src/test/files/checks/java/ThreadSafeFieldCheckDsComponentAnnotation.java"; - verify(); - } - - @Test - public void checkThreadSafeFieldsInSlingServletAnnotated() { - check = new ThreadSafeFieldCheck(); - filename = "src/test/files/checks/java/ThreadSafeFieldCheckSlingServletAnnotation.java"; - verify(); - } -} diff --git a/src/test/java/com/cognifide/aemrules/version/VersionSupportCheckerTest.java b/src/test/java/com/cognifide/aemrules/version/VersionSupportCheckerTest.java deleted file mode 100644 index abf2b0b8..00000000 --- a/src/test/java/com/cognifide/aemrules/version/VersionSupportCheckerTest.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * #%L - * AEM Rules for SonarQube - * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ -package com.cognifide.aemrules.version; - -import static com.cognifide.aemrules.version.VersionSupportChecker.DEFAULT_AEM_VERSION; -import static com.cognifide.aemrules.version.VersionSupportChecker.create; -import static org.hamcrest.CoreMatchers.is; - -import org.junit.Assert; -import org.junit.Test; - -public class VersionSupportCheckerTest { - - @Test - public void shouldSupportAllVersionsWhenAllSet() { - VersionSupportChecker versionSupportChecker = create( - CheckSupportingAllVersions.class.getAnnotation(AemVersion.class)); - Assert.assertThat(versionSupportChecker.supports("6.3"), is(true)); - Assert.assertThat(versionSupportChecker.supports("2.1"), is(true)); - Assert.assertThat(versionSupportChecker.supports("2.0"), is(true)); - } - - @Test - public void shouldSupportAllVersionsBetweenFromAndTo() { - VersionSupportChecker versionSupportChecker = create( - CheckSupportingVersionsFromTo.class.getAnnotation(AemVersion.class)); - Assert.assertThat(versionSupportChecker.supports("6.1"), is(true)); - Assert.assertThat(versionSupportChecker.supports("5.2"), is(true)); - Assert.assertThat(versionSupportChecker.supports("5.1"), is(true)); - Assert.assertThat(versionSupportChecker.supports("6.4"), is(true)); - Assert.assertThat(versionSupportChecker.supports("6.5"), is(false)); - Assert.assertThat(versionSupportChecker.supports("5.0"), is(false)); - } - - @Test - public void shouldSupportAllVersionsFrom() { - VersionSupportChecker versionSupportChecker = create( - CheckSupportingVersionsFrom.class.getAnnotation(AemVersion.class)); - Assert.assertThat(versionSupportChecker.supports("100.1"), is(true)); - Assert.assertThat(versionSupportChecker.supports("10.1"), is(true)); - Assert.assertThat(versionSupportChecker.supports("17.2"), is(true)); - Assert.assertThat(versionSupportChecker.supports("10.0"), is(false)); - Assert.assertThat(versionSupportChecker.supports("5.9"), is(false)); - } - - @Test - public void shouldSupportAllVersionsTo() { - VersionSupportChecker supportedVersions = create( - CheckSupportingVersionsTo.class.getAnnotation(AemVersion.class)); - Assert.assertThat(supportedVersions.supports("1.1"), is(true)); - Assert.assertThat(supportedVersions.supports("10.1"), is(true)); - Assert.assertThat(supportedVersions.supports("0.2"), is(true)); - Assert.assertThat(supportedVersions.supports("8.5"), is(true)); - Assert.assertThat(supportedVersions.supports("10.2"), is(false)); - Assert.assertThat(supportedVersions.supports("20.9"), is(false)); - } - - @Test - public void shouldSupportAllProvidedVersions() { - VersionSupportChecker supportedVersions = create( - CheckSupportingVersionsIncluded.class.getAnnotation(AemVersion.class)); - Assert.assertThat(supportedVersions.supports("6.1"), is(true)); - Assert.assertThat(supportedVersions.supports("2.1"), is(true)); - Assert.assertThat(supportedVersions.supports("4.8"), is(true)); - Assert.assertThat(supportedVersions.supports("6.0"), is(false)); - Assert.assertThat(supportedVersions.supports("2.2"), is(false)); - } - - @Test - public void shouldSupportAllVersionsExcludingProvided() { - VersionSupportChecker supportedVersions = create( - CheckSupportingVersionsExcluded.class.getAnnotation(AemVersion.class)); - Assert.assertThat(supportedVersions.supports("6.1"), is(false)); - Assert.assertThat(supportedVersions.supports("2.1"), is(false)); - Assert.assertThat(supportedVersions.supports("4.8"), is(false)); - Assert.assertThat(supportedVersions.supports("6.0"), is(true)); - Assert.assertThat(supportedVersions.supports("2.2"), is(true)); - } - - @Test - public void shouldUseDefaultVersionWhenProvidedVersionIsEmptyOrNull() { - VersionSupportChecker supportedVersions = create( - CheckSupportingDefaultVersion.class.getAnnotation(AemVersion.class)); - Assert.assertThat(supportedVersions.supports(DEFAULT_AEM_VERSION), is(true)); - Assert.assertThat(supportedVersions.supports(""), is(true)); - Assert.assertThat(supportedVersions.supports(null), is(true)); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionWhenVersionToSupportIsIncorrect() { - VersionSupportChecker supportedVersions = create( - CheckSupportingVersionsExcluded.class.getAnnotation(AemVersion.class)); - supportedVersions.supports("f.1"); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionWhenVersionIncorrectProvided1() { - create(CheckWithIncorrectVersion1.class.getAnnotation(AemVersion.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionWhenVersionIncorrectProvided2() { - create(CheckWithIncorrectVersion2.class.getAnnotation(AemVersion.class)); - } - - - @AemVersion( - all = true - ) - private class CheckSupportingAllVersions { - - } - - @AemVersion( - from = "5.1", - to = "6.4" - ) - private class CheckSupportingVersionsFromTo { - - } - - @AemVersion( - from = "10.1" - ) - private class CheckSupportingVersionsFrom { - - } - - @AemVersion( - to = "10.1" - ) - private class CheckSupportingVersionsTo { - - } - - @AemVersion( - included = {"6.1", "2.1", "4.8"} - ) - private class CheckSupportingVersionsIncluded { - - } - - @AemVersion( - all = true, - excluded = {"6.1", "2.1", "4.8"} - ) - private class CheckSupportingVersionsExcluded { - - } - - @AemVersion( - from = "5.6.7" - ) - private class CheckWithIncorrectVersion1 { - - } - - @AemVersion( - included = "a.b" - ) - private class CheckWithIncorrectVersion2 { - - } - - @AemVersion( - included = {DEFAULT_AEM_VERSION} - ) - private class CheckSupportingDefaultVersion { - - } - -} \ No newline at end of file diff --git a/src/test/java/com/cognifide/aemrules/AemRulesSonarPluginTest.java b/src/test/java/com/vml/aemrules/AemRulesSonarPluginTest.java similarity index 77% rename from src/test/java/com/cognifide/aemrules/AemRulesSonarPluginTest.java rename to src/test/java/com/vml/aemrules/AemRulesSonarPluginTest.java index 6118d6e7..fb89a800 100644 --- a/src/test/java/com/cognifide/aemrules/AemRulesSonarPluginTest.java +++ b/src/test/java/com/vml/aemrules/AemRulesSonarPluginTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,25 +17,24 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules; +package com.vml.aemrules; -import static org.fest.assertions.Assertions.assertThat; - -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.sonar.api.Plugin; import org.sonar.api.SonarEdition; import org.sonar.api.SonarQubeSide; import org.sonar.api.internal.SonarRuntimeImpl; import org.sonar.api.utils.Version; -public class AemRulesSonarPluginTest { +import static org.assertj.core.api.Assertions.assertThat; + +class AemRulesSonarPluginTest { @Test - public void webPluginTester() { + void webPluginTester() { Plugin.Context context = new Plugin.Context(SonarRuntimeImpl.forSonarQube(Version.create(6, 7), SonarQubeSide.SERVER, SonarEdition.COMMUNITY)); new AemRulesSonarPlugin().define(context); - assertThat(context.getExtensions()).hasSize(7); + assertThat(context.getExtensions()).hasSize(8); } - -} \ No newline at end of file +} diff --git a/src/test/java/com/cognifide/aemrules/htl/AbstractBaseTest.java b/src/test/java/com/vml/aemrules/htl/AbstractBaseTest.java similarity index 75% rename from src/test/java/com/cognifide/aemrules/htl/AbstractBaseTest.java rename to src/test/java/com/vml/aemrules/htl/AbstractBaseTest.java index a2ac1aae..b76bdfc8 100644 --- a/src/test/java/com/cognifide/aemrules/htl/AbstractBaseTest.java +++ b/src/test/java/com/vml/aemrules/htl/AbstractBaseTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,29 +17,30 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; -import com.cognifide.aemrules.htl.api.HtlCheck; -import com.cognifide.aemrules.htl.checks.AbstractHtlCheck; -import com.cognifide.aemrules.htl.lex.HtlLexer; -import com.cognifide.aemrules.htl.rules.HtlCheckClasses; -import com.cognifide.aemrules.htl.visitors.HtlScanner; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.List; - -import com.cognifide.aemrules.utils.Throwables; +import com.vml.aemrules.htl.api.HtlCheck; +import com.vml.aemrules.htl.checks.AbstractHtlCheck; +import com.vml.aemrules.htl.lex.HtlLexer; +import com.vml.aemrules.htl.rules.HtlRulesList; +import com.vml.aemrules.htl.visitors.HtlScanner; +import com.vml.aemrules.utils.Throwables; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.api.rule.RuleKey; import org.sonar.check.Rule; -import org.sonar.plugins.html.api.HtmlConstants; import org.sonar.plugins.html.checks.HtmlIssue; import org.sonar.plugins.html.node.CommentNode; import org.sonar.plugins.html.visitor.HtmlSourceCode; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; + +import static com.vml.aemrules.htl.Constants.REPOSITORY_KEY; + public abstract class AbstractBaseTest { protected AbstractHtlCheck check; @@ -48,12 +49,12 @@ public abstract class AbstractBaseTest { private static HtmlSourceCode createSourceCode(File file) { return new HtmlSourceCode( - new TestInputFileBuilder("key", file.getPath()) - .setLanguage(HtmlConstants.LANGUAGE_KEY) - .setType(InputFile.Type.MAIN) - .setModuleBaseDir(new File(".").toPath()) - .setCharset(StandardCharsets.UTF_8) - .build() + new TestInputFileBuilder("key", file.getPath()) + .setLanguage(Htl.LANGUAGE_KEY) + .setType(InputFile.Type.MAIN) + .setModuleBaseDir(new File(".").toPath()) + .setCharset(StandardCharsets.UTF_8) + .build() ); } @@ -62,8 +63,8 @@ private static HtlScanner setupScanner(AbstractHtlCheck check, HtmlCheckVerifier scanner.addVisitor(new ExpectedIssueCollector(htmlCheckVerifier)); if (check != null) { Class htlCheck = check.getClass(); - Rule rule = HtlCheckClasses.getRule(htlCheck); - RuleKey ruleKey = RuleKey.of(HtlCheckClasses.REPOSITORY_KEY, rule.key()); + Rule rule = HtlRulesList.getRule(htlCheck); + RuleKey ruleKey = RuleKey.of(REPOSITORY_KEY, rule.key()); check.setRuleKey(ruleKey); } scanner.addVisitor(check); diff --git a/src/test/java/com/cognifide/aemrules/htl/HtlProfileTest.java b/src/test/java/com/vml/aemrules/htl/HtlProfileTest.java similarity index 71% rename from src/test/java/com/cognifide/aemrules/htl/HtlProfileTest.java rename to src/test/java/com/vml/aemrules/htl/HtlProfileTest.java index 733fc0e5..2168802f 100644 --- a/src/test/java/com/cognifide/aemrules/htl/HtlProfileTest.java +++ b/src/test/java/com/vml/aemrules/htl/HtlProfileTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,37 +17,37 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; -import static org.fest.assertions.Assertions.assertThat; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.BuiltInActiveRule; +import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.BuiltInQualityProfile; +import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.Context; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.function.Function; import java.util.stream.Collectors; -import org.junit.Before; -import org.junit.Test; -import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition; -import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.BuiltInActiveRule; -import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.BuiltInQualityProfile; -import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.Context; -public class HtlProfileTest { +import static org.assertj.core.api.Assertions.assertThat; + +class HtlProfileTest { private HtlProfile profile; private Context context; - @Before + @BeforeEach public void setUp() { profile = new HtlProfile(); - this.context = new BuiltInQualityProfilesDefinition.Context(); + this.context = new Context(); } @Test - public void sanity() { + void sanity() { profile.define(context); Map activeRules = getActiveRulesByRuleKey(context); @@ -56,7 +56,7 @@ public void sanity() { } @Test - public void rulesLoaded() { + void rulesLoaded() { profile.define(context); Map activeRules = getActiveRulesByRuleKey(context); @@ -67,13 +67,13 @@ public void rulesLoaded() { private Map getActiveRulesByRuleKey(Context context) { return context.profilesByLanguageAndName().entrySet().stream() - .map(Entry::getValue) - .map(Map::entrySet) - .flatMap(Collection::stream) - .map(Entry::getValue) - .map(BuiltInQualityProfile::rules) - .flatMap(Collection::stream) - .collect(Collectors.toMap(BuiltInActiveRule::ruleKey, Function.identity())); + .map(Entry::getValue) + .map(Map::entrySet) + .flatMap(Collection::stream) + .map(Entry::getValue) + .map(BuiltInQualityProfile::rules) + .flatMap(Collection::stream) + .collect(Collectors.toMap(BuiltInActiveRule::ruleKey, Function.identity())); } } diff --git a/src/test/java/com/cognifide/aemrules/htl/HtlSensorTest.java b/src/test/java/com/vml/aemrules/htl/HtlSensorTest.java similarity index 74% rename from src/test/java/com/cognifide/aemrules/htl/HtlSensorTest.java rename to src/test/java/com/vml/aemrules/htl/HtlSensorTest.java index c12383d4..611fb7e4 100644 --- a/src/test/java/com/cognifide/aemrules/htl/HtlSensorTest.java +++ b/src/test/java/com/vml/aemrules/htl/HtlSensorTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,25 +17,16 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; -import static org.fest.assertions.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.cognifide.aemrules.extensions.AemRulesRulesDefinition; -import com.cognifide.aemrules.htl.checks.HtlAttributesShouldBeAtTheEndCheck; -import com.cognifide.aemrules.htl.rules.HtlCheckClasses; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; -import org.junit.Before; -import org.junit.Test; +import com.vml.aemrules.htl.checks.HtlAttributesShouldBeAtTheEndCheck; +import com.vml.aemrules.htl.rules.HtlRulesDefinition; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.sonar.api.SonarEdition; +import org.sonar.api.SonarQubeSide; +import org.sonar.api.SonarRuntime; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; @@ -46,15 +37,29 @@ import org.sonar.api.batch.sensor.internal.SensorContextTester; import org.sonar.api.batch.sensor.issue.Issue; import org.sonar.api.config.Configuration; +import org.sonar.api.internal.SonarRuntimeImpl; import org.sonar.api.measures.FileLinesContext; import org.sonar.api.measures.FileLinesContextFactory; import org.sonar.api.rule.RuleKey; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.api.server.rule.RulesDefinition.Repository; -import org.sonar.plugins.html.api.HtmlConstants; +import org.sonar.api.utils.Version; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import static com.vml.aemrules.htl.Constants.REPOSITORY_KEY; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -public class HtlSensorTest { +class HtlSensorTest { private static final File TEST_DIR = new File("src/test/resources/sensor"); @@ -62,12 +67,13 @@ public class HtlSensorTest { private SensorContextTester tester; - @Before - public void setUp() { - RulesDefinition rulesDefinition = new AemRulesRulesDefinition(); + @BeforeEach + void setUp() { + SonarRuntime sonarRuntime = SonarRuntimeImpl.forSonarQube(Version.create(8, 9), SonarQubeSide.SERVER, SonarEdition.COMMUNITY); + RulesDefinition rulesDefinition = new HtlRulesDefinition(sonarRuntime); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); - RulesDefinition.Repository htlRepository = context.repository(HtlCheckClasses.REPOSITORY_KEY); + Repository htlRepository = context.repository(REPOSITORY_KEY); FileLinesContextFactory fileLinesContextFactory = getMockedFileLinesContextFactory(); Configuration configuration = getMockedConfiguration(); @@ -80,7 +86,7 @@ public void setUp() { private CheckFactory getCheckFactory(Repository htlRepository) { List ar = new ArrayList<>(); for (RulesDefinition.Rule rule : htlRepository.rules()) { - ar.add(new NewActiveRule.Builder().setRuleKey(RuleKey.of(HtlCheckClasses.REPOSITORY_KEY, rule.key())).build()); + ar.add(new NewActiveRule.Builder().setRuleKey(RuleKey.of(REPOSITORY_KEY, rule.key())).build()); } return new CheckFactory(new DefaultActiveRules(ar)); } @@ -99,21 +105,21 @@ private FileLinesContextFactory getMockedFileLinesContextFactory() { } @Test - public void checkIncorrectFile_issuesFound() throws Exception { + void checkIncorrectFile_issuesFound() throws Exception { DefaultInputFile inputFile = createInputFile(TEST_DIR, "test.html"); tester.fileSystem().add(inputFile); sensor.execute(tester); assertThat(tester.allIssues()).isNotEmpty(); List issuesRules = tester.allIssues().stream() - .map(Issue::ruleKey) - .map(RuleKey::rule) - .distinct() - .collect(Collectors.toList()); + .map(Issue::ruleKey) + .map(RuleKey::rule) + .distinct() + .collect(Collectors.toList()); assertThat(issuesRules).contains(HtlAttributesShouldBeAtTheEndCheck.RULE_KEY); } @Test - public void checkCancellation_noIssueFound() throws Exception { + void checkCancellation_noIssueFound() throws Exception { DefaultInputFile inputFile = createInputFile(TEST_DIR, "test.html"); tester.fileSystem().add(inputFile); tester.setCancelled(true); @@ -122,7 +128,7 @@ public void checkCancellation_noIssueFound() throws Exception { } @Test - public void sonarlintCheck() throws Exception { + void sonarlintCheck() throws Exception { DefaultInputFile inputFile = createInputFile(TEST_DIR, "test.html"); tester.fileSystem().add(inputFile); sensor.execute(tester); @@ -133,7 +139,7 @@ public void sonarlintCheck() throws Exception { } @Test - public void checkFileWithError_analysisErrorFound() throws Exception { + void checkFileWithError_analysisErrorFound() throws Exception { DefaultInputFile inputFile = createInputFile(TEST_DIR, "error.html"); tester.fileSystem().add(inputFile); sensor.execute(tester); @@ -141,7 +147,7 @@ public void checkFileWithError_analysisErrorFound() throws Exception { } @Test - public void checkExpressionWithinHtmlComment_noErrorsFound() throws Exception { + void checkExpressionWithinHtmlComment_noErrorsFound() throws Exception { DefaultInputFile inputFile = createInputFile(TEST_DIR, "comment.html"); tester.fileSystem().add(inputFile); sensor.execute(tester); @@ -149,7 +155,7 @@ public void checkExpressionWithinHtmlComment_noErrorsFound() throws Exception { } @Test - public void checkNestedTags_noErrorsFound() throws IOException { + void checkNestedTags_noErrorsFound() throws IOException { DefaultInputFile inputFile = createInputFile(TEST_DIR, "nestedTags.html"); tester.fileSystem().add(inputFile); sensor.execute(tester); @@ -157,7 +163,7 @@ public void checkNestedTags_noErrorsFound() throws IOException { } @Test - public void checkDescriptorConfiguration() { + void checkDescriptorConfiguration() { DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor(); sensor.describe(descriptor); assertThat(descriptor.name()).isEqualTo("HTL"); @@ -166,12 +172,12 @@ public void checkDescriptorConfiguration() { private DefaultInputFile createInputFile(File dir, String fileName) throws IOException { return new TestInputFileBuilder("key", fileName) - .setModuleBaseDir(dir.toPath()) - .setLanguage(HtmlConstants.LANGUAGE_KEY) - .setType(InputFile.Type.MAIN) - .initMetadata(new String(Files.readAllBytes(new File(dir, fileName).toPath()), StandardCharsets.UTF_8)) - .setCharset(StandardCharsets.UTF_8) - .build(); + .setModuleBaseDir(dir.toPath()) + .setLanguage(Htl.LANGUAGE_KEY) + .setType(InputFile.Type.MAIN) + .initMetadata(new String(Files.readAllBytes(new File(dir, fileName).toPath()), StandardCharsets.UTF_8)) + .setCharset(StandardCharsets.UTF_8) + .build(); } -} \ No newline at end of file +} diff --git a/src/test/java/com/cognifide/aemrules/htl/HtlTest.java b/src/test/java/com/vml/aemrules/htl/HtlTest.java similarity index 73% rename from src/test/java/com/cognifide/aemrules/htl/HtlTest.java rename to src/test/java/com/vml/aemrules/htl/HtlTest.java index 146e3475..abb4c0ab 100644 --- a/src/test/java/com/cognifide/aemrules/htl/HtlTest.java +++ b/src/test/java/com/vml/aemrules/htl/HtlTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,18 +17,18 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; +import org.junit.jupiter.api.Test; -import static org.fest.assertions.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; -public class HtlTest { +class HtlTest { @Test - public void shouldReturnEmptyArrayOfDefaultFileSuffixes() { + void shouldReturnEmptyArrayOfDefaultFileSuffixes() { Htl htl = new Htl(); assertThat(htl.getFileSuffixes()).isEmpty(); } -} \ No newline at end of file +} diff --git a/src/test/java/com/cognifide/aemrules/htl/HtmlCheckVerifier.java b/src/test/java/com/vml/aemrules/htl/HtmlCheckVerifier.java similarity index 85% rename from src/test/java/com/cognifide/aemrules/htl/HtmlCheckVerifier.java rename to src/test/java/com/vml/aemrules/htl/HtmlCheckVerifier.java index 0354d166..78517e5a 100644 --- a/src/test/java/com/cognifide/aemrules/htl/HtmlCheckVerifier.java +++ b/src/test/java/com/vml/aemrules/htl/HtmlCheckVerifier.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,23 +17,24 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; - -import static org.junit.Assert.assertThat; -import static org.junit.matchers.JUnitMatchers.hasItem; +import org.apache.commons.lang3.StringUtils; +import org.sonar.plugins.html.checks.HtmlIssue; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; -import org.apache.commons.lang3.StringUtils; -import org.sonar.plugins.html.checks.HtmlIssue; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.MatcherAssert.assertThat; + public class HtmlCheckVerifier { public static final String ISSUE_MARKER = ""; - private Set expectedIssuesLines; + private final Set expectedIssuesLines; public HtmlCheckVerifier() { this.expectedIssuesLines = new HashSet<>(); @@ -48,8 +49,8 @@ public void collectExpectedIssues(String comment, int startLine) { public void checkIssues(List issues) { Set issuesLines = issues.stream() - .map(HtmlIssue::line) - .collect(Collectors.toSet()); + .map(HtmlIssue::line) + .collect(Collectors.toSet()); for (HtmlIssue issue : issues) { assertThat("No issues expected in line: " + issue.line() + ", but got: " + issue.ruleKey(), expectedIssuesLines, hasItem(issue.line())); diff --git a/src/test/java/com/cognifide/aemrules/htl/HtmlCheckVerifierTest.java b/src/test/java/com/vml/aemrules/htl/HtmlCheckVerifierTest.java similarity index 67% rename from src/test/java/com/cognifide/aemrules/htl/HtmlCheckVerifierTest.java rename to src/test/java/com/vml/aemrules/htl/HtmlCheckVerifierTest.java index c2082bc4..5bc759b7 100644 --- a/src/test/java/com/cognifide/aemrules/htl/HtmlCheckVerifierTest.java +++ b/src/test/java/com/vml/aemrules/htl/HtmlCheckVerifierTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,49 +17,53 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl; +package com.vml.aemrules.htl; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.sonar.api.rule.RuleKey; +import org.sonar.plugins.html.checks.HtmlIssue; import java.util.ArrayList; import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.sonar.api.rule.RuleKey; -import org.sonar.plugins.html.checks.HtmlIssue; -public class HtmlCheckVerifierTest { +import static org.junit.jupiter.api.Assertions.assertThrows; - private HtmlCheckVerifier htmlCheckVerifier = new HtmlCheckVerifier(); +class HtmlCheckVerifierTest { - @Before + private final HtmlCheckVerifier htmlCheckVerifier = new HtmlCheckVerifier(); + + @BeforeEach public void setUp() { htmlCheckVerifier.collectExpectedIssues(HtmlCheckVerifier.ISSUE_MARKER, 1); } - @Test(expected = AssertionError.class) - public void checkUnexpectedError() { + @Test + void checkUnexpectedError() { List htmlIssues = new ArrayList<>(); htmlIssues.add(createLineIssue(1)); htmlIssues.add(createLineIssue(2)); - htmlCheckVerifier.checkIssues(htmlIssues); + assertThrows(AssertionError.class, () -> { + htmlCheckVerifier.checkIssues(htmlIssues); + }); } - @Test() - public void checkMultipleExpectedIssuesInTheSameLine() { + @Test + void checkMultipleExpectedIssuesInTheSameLine() { List htmlIssues = new ArrayList<>(); htmlIssues.add(createLineIssue(1)); htmlIssues.add(createLineIssue(1)); htmlCheckVerifier.checkIssues(htmlIssues); } - @Test(expected = AssertionError.class) - public void checkExpectedIssueButNotReported() { + @Test + void checkExpectedIssueButNotReported() { List htmlIssues = new ArrayList<>(); - htmlCheckVerifier.checkIssues(htmlIssues); + assertThrows(AssertionError.class, () -> htmlCheckVerifier.checkIssues(htmlIssues)); } private HtmlIssue createLineIssue(Integer line) { RuleKey rule = RuleKey.of("r", "r"); return new HtmlIssue(rule, line, ""); } -} \ No newline at end of file +} diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/AbstractHtlCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/AbstractHtlCheckTest.java similarity index 50% rename from src/test/java/com/cognifide/aemrules/htl/checks/AbstractHtlCheckTest.java rename to src/test/java/com/vml/aemrules/htl/checks/AbstractHtlCheckTest.java index 27b825e9..c24562f2 100644 --- a/src/test/java/com/cognifide/aemrules/htl/checks/AbstractHtlCheckTest.java +++ b/src/test/java/com/vml/aemrules/htl/checks/AbstractHtlCheckTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,41 +17,52 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; - -import static org.fest.assertions.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import java.io.File; -import java.util.List; -import org.junit.Before; -import org.junit.Test; +import com.vml.aemrules.htl.AbstractBaseTest; +import com.vml.aemrules.htl.Htl; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.plugins.html.checks.HtmlIssue; import org.sonar.plugins.html.visitor.HtmlSourceCode; -public class AbstractHtlCheckTest { +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; - private AbstractHtlCheck check; - private HtmlSourceCode htmlSourceCode; +class AbstractHtlCheckTest extends AbstractBaseTest { - private static HtmlSourceCode createHtmlSourceCode(String relativePath) { - return new HtmlSourceCode(new TestInputFileBuilder("key", relativePath).setModuleBaseDir(new File(".").toPath()).build()); + private AbstractHtlCheck check; + + private static HtmlSourceCode createHtmlSourceCode(File file) { + return new HtmlSourceCode( + new TestInputFileBuilder("key", file.getPath()) + .setLanguage(Htl.LANGUAGE_KEY) + .setType(InputFile.Type.MAIN) + .setModuleBaseDir(new File(".").toPath()) + .setCharset(StandardCharsets.UTF_8) + .build() + ); } - @Before + @BeforeEach public void setUp() { this.check = new AbstractHtlCheck(); - this.htmlSourceCode = createHtmlSourceCode("/"); - check.setSourceCode(htmlSourceCode); + File file = new File("src/test/files/htl/Empty.html"); + HtmlSourceCode htmlSourceCode = createHtmlSourceCode(file); + this.check.setSourceCode(htmlSourceCode); } @Test - public void creatingViolationWithoutCost() { - check.createViolation(0, "Issue 0"); + void creatingViolationWithoutCost() { + this.check.createViolation(0, "Issue 0"); List issues = check.getHtmlSourceCode().getIssues(); assertThat(issues).hasSize(1); @@ -59,8 +70,8 @@ public void creatingViolationWithoutCost() { } @Test - public void creatingViolationWithCost() { - check.createViolation(1, "Issue 0", 1d); + void creatingViolationWithCost() { + this.check.createViolation(1, "Issue 0", 1d); List issues = check.getHtmlSourceCode().getIssues(); assertThat(issues).hasSize(1); @@ -68,9 +79,9 @@ public void creatingViolationWithCost() { } @Test - public void creatingViolations() { - check.createViolation(0, "Issue 0", 1d); - check.createViolation(1, "Issue 1"); + void creatingViolations() { + this.check.createViolation(0, "Issue 0", 1d); + this.check.createViolation(1, "Issue 1"); List issues = check.getHtmlSourceCode().getIssues(); assertThat(issues).hasSize(2); @@ -78,5 +89,4 @@ public void creatingViolations() { assertNull(issues.get(1).cost()); } - -} \ No newline at end of file +} diff --git a/src/test/java/com/vml/aemrules/htl/checks/AvoidExtraSlyTagsCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/AvoidExtraSlyTagsCheckTest.java new file mode 100644 index 00000000..f4dbb6ad --- /dev/null +++ b/src/test/java/com/vml/aemrules/htl/checks/AvoidExtraSlyTagsCheckTest.java @@ -0,0 +1,33 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.checks; + +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; + +class AvoidExtraSlyTagsCheckTest extends AbstractBaseTest { + + @Test + void avoidExtraSlyTags() { + this.check = new AvoidExtraSlyTagsCheck(); + this.filename = "src/test/files/htl/AvoidExtraSlyTagsCheck.html"; + verify(); + } +} diff --git a/src/test/java/com/vml/aemrules/htl/checks/AvoidUsingUnsafeDisplayContextCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/AvoidUsingUnsafeDisplayContextCheckTest.java new file mode 100644 index 00000000..1940e8a6 --- /dev/null +++ b/src/test/java/com/vml/aemrules/htl/checks/AvoidUsingUnsafeDisplayContextCheckTest.java @@ -0,0 +1,33 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.checks; + +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; + +class AvoidUsingUnsafeDisplayContextCheckTest extends AbstractBaseTest { + + @Test + void checkAllDataAttributesContainsDisplayContext() { + this.check = new AvoidUsingUnsafeDisplayContextCheck(); + this.filename = "src/test/files/htl/AvoidUsingUnsafeDisplayContextCheck.html"; + verify(); + } +} diff --git a/src/test/java/com/vml/aemrules/htl/checks/CamelCaseCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/CamelCaseCheckTest.java new file mode 100644 index 00000000..9b78d151 --- /dev/null +++ b/src/test/java/com/vml/aemrules/htl/checks/CamelCaseCheckTest.java @@ -0,0 +1,33 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.checks; + +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; + +class CamelCaseCheckTest extends AbstractBaseTest { + + @Test + void checkCapitalization() { + this.check = new CamelCaseCheck(); + this.filename = "src/test/files/htl/CamelCaseCheck.html"; + verify(); + } +} diff --git a/src/test/java/com/cognifide/aemrules/java/checks/ModifiableValueMapUsageCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/DefaultDisplayContextCheckTest.java similarity index 62% rename from src/test/java/com/cognifide/aemrules/java/checks/ModifiableValueMapUsageCheckTest.java rename to src/test/java/com/vml/aemrules/htl/checks/DefaultDisplayContextCheckTest.java index 16298d6e..9fb6b390 100644 --- a/src/test/java/com/cognifide/aemrules/java/checks/ModifiableValueMapUsageCheckTest.java +++ b/src/test/java/com/vml/aemrules/htl/checks/DefaultDisplayContextCheckTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,16 +17,17 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; +package com.vml.aemrules.htl.checks; -import org.junit.Test; +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; -public class ModifiableValueMapUsageCheckTest extends AbstractBaseTest { +class DefaultDisplayContextCheckTest extends AbstractBaseTest { @Test - public void checkIfMVMIsUsedToRetrievePropertiesFromResource() { - check = new ModifiableValueMapUsageCheck(); - filename = "src/test/files/checks/java/ModifiableValueMapUsageCheck.java"; + void checkDefaultDisplayContext() { + this.check = new DefaultDisplayContextCheck(); + this.filename = "src/test/files/htl/UseDefaultDisplayContextCheck.html"; verify(); } } diff --git a/src/test/java/com/vml/aemrules/htl/checks/DisplayContextInConditionalCommentsCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/DisplayContextInConditionalCommentsCheckTest.java new file mode 100644 index 00000000..fe0f9af3 --- /dev/null +++ b/src/test/java/com/vml/aemrules/htl/checks/DisplayContextInConditionalCommentsCheckTest.java @@ -0,0 +1,33 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.checks; + +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; + +class DisplayContextInConditionalCommentsCheckTest extends AbstractBaseTest { + + @Test + void checkContextInConditionalComments() { + this.check = new DisplayContextInConditionalCommentsCheck(); + this.filename = "src/test/files/htl/DisplayContextInConditionalCommentsCheck.html"; + verify(); + } +} diff --git a/src/test/java/com/vml/aemrules/htl/checks/DisplayContextIsMandatoryForInlineStylesCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/DisplayContextIsMandatoryForInlineStylesCheckTest.java new file mode 100644 index 00000000..83cfe610 --- /dev/null +++ b/src/test/java/com/vml/aemrules/htl/checks/DisplayContextIsMandatoryForInlineStylesCheckTest.java @@ -0,0 +1,33 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.checks; + +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; + +class DisplayContextIsMandatoryForInlineStylesCheckTest extends AbstractBaseTest { + + @Test + void checkInlineStyleDisplayContext() { + this.check = new InlineStyleMandatoryDisplayContextCheck(); + this.filename = "src/test/files/htl/DefineDisplayContextInInlineStylesCheck.html"; + verify(); + } +} diff --git a/src/test/java/com/vml/aemrules/htl/checks/DisplayContextIsMandatoryInEventAttributesTest.java b/src/test/java/com/vml/aemrules/htl/checks/DisplayContextIsMandatoryInEventAttributesTest.java new file mode 100644 index 00000000..03a63647 --- /dev/null +++ b/src/test/java/com/vml/aemrules/htl/checks/DisplayContextIsMandatoryInEventAttributesTest.java @@ -0,0 +1,33 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.checks; + +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; + +class DisplayContextIsMandatoryInEventAttributesTest extends AbstractBaseTest { + + @Test + void checkEventAttributeDisplayContext() { + this.check = new EventMandatoryDisplayContextCheck(); + this.filename = "src/test/files/htl/DefineDisplayContextInEventAttributes.html"; + verify(); + } +} diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/SlyElementsAreAutomaticallyUnwrappedCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/DisplayContextIsMandatoryInScriptsAndStylesCheckTest.java similarity index 60% rename from src/test/java/com/cognifide/aemrules/htl/checks/SlyElementsAreAutomaticallyUnwrappedCheckTest.java rename to src/test/java/com/vml/aemrules/htl/checks/DisplayContextIsMandatoryInScriptsAndStylesCheckTest.java index eda5d43c..67e50c56 100644 --- a/src/test/java/com/cognifide/aemrules/htl/checks/SlyElementsAreAutomaticallyUnwrappedCheckTest.java +++ b/src/test/java/com/vml/aemrules/htl/checks/DisplayContextIsMandatoryInScriptsAndStylesCheckTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,17 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; -public class SlyElementsAreAutomaticallyUnwrappedCheckTest extends AbstractBaseTest { +class DisplayContextIsMandatoryInScriptsAndStylesCheckTest extends AbstractBaseTest { @Test - public void checkRedundantUnwrapAttributes() { - check = new SlyElementsAreAutomaticallyUnwrappedCheck(); - filename = "src/test/files/checks/htl/SlyElementsAreAutomaticallyUnwrappedCheck.html"; + void checkScriptsAndStyleDisplayContext() { + this.check = new ScriptsAndStyleMandatoryDisplayContextCheck(); + this.filename = "src/test/files/htl/DefineDisplayContextInScriptsAndStylesCheck.html"; verify(); } } diff --git a/src/test/java/com/vml/aemrules/htl/checks/ExplicitNamesInLoopsCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/ExplicitNamesInLoopsCheckTest.java new file mode 100644 index 00000000..84dbb9d3 --- /dev/null +++ b/src/test/java/com/vml/aemrules/htl/checks/ExplicitNamesInLoopsCheckTest.java @@ -0,0 +1,33 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.checks; + +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; + +class ExplicitNamesInLoopsCheckTest extends AbstractBaseTest { + + @Test + void ExplicitNamesInLoopsCheck() { + this.check = new ExplicitNamesInLoopsCheck(); + this.filename = "src/test/files/htl/ExplicitNamesInLoopsCheck.html"; + verify(); + } +} diff --git a/src/test/java/com/vml/aemrules/htl/checks/HtlAttributesShouldBeAtTheEndCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/HtlAttributesShouldBeAtTheEndCheckTest.java new file mode 100644 index 00000000..3a0cdc0e --- /dev/null +++ b/src/test/java/com/vml/aemrules/htl/checks/HtlAttributesShouldBeAtTheEndCheckTest.java @@ -0,0 +1,33 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.checks; + +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; + +class HtlAttributesShouldBeAtTheEndCheckTest extends AbstractBaseTest { + + @Test + void checkHtlAttributesOrder() { + this.check = new HtlAttributesShouldBeAtTheEndCheck(); + this.filename = "src/test/files/htl/HtlAttributesShouldBeAtTheEndCheck.html"; + verify(); + } +} diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/CamelCaseCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/HtlCommentsCheckTest.java similarity index 63% rename from src/test/java/com/cognifide/aemrules/htl/checks/CamelCaseCheckTest.java rename to src/test/java/com/vml/aemrules/htl/checks/HtlCommentsCheckTest.java index 30068220..f05af07e 100644 --- a/src/test/java/com/cognifide/aemrules/htl/checks/CamelCaseCheckTest.java +++ b/src/test/java/com/vml/aemrules/htl/checks/HtlCommentsCheckTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,18 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; +package com.vml.aemrules.htl.checks; -public class CamelCaseCheckTest extends AbstractBaseTest { +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; + +class HtlCommentsCheckTest extends AbstractBaseTest { @Test - public void checkCapitalization() { - check = new CamelCaseCheck(); - filename = "src/test/files/checks/htl/CamelCaseCheck.html"; + void checkHTLStyleOfCommenting() { + this.check = new HtlCommentsCheck(); + this.filename = "src/test/files/htl/HtlCommentsCheck.html"; verify(); } -} \ No newline at end of file +} diff --git a/src/test/java/com/vml/aemrules/htl/checks/NamingAndReusingConditionsCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/NamingAndReusingConditionsCheckTest.java new file mode 100644 index 00000000..339011dc --- /dev/null +++ b/src/test/java/com/vml/aemrules/htl/checks/NamingAndReusingConditionsCheckTest.java @@ -0,0 +1,33 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.checks; + +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; + +class NamingAndReusingConditionsCheckTest extends AbstractBaseTest { + + @Test + void checkHtlAttributesOrder() { + this.check = new NamingAndReusingConditionsCheck(); + this.filename = "src/test/files/htl/NamingAndReusingConditionsCheck.html"; + verify(); + } +} diff --git a/src/test/java/com/vml/aemrules/htl/checks/PlaceTemplatesInSeparateFilesCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/PlaceTemplatesInSeparateFilesCheckTest.java new file mode 100644 index 00000000..a76a96da --- /dev/null +++ b/src/test/java/com/vml/aemrules/htl/checks/PlaceTemplatesInSeparateFilesCheckTest.java @@ -0,0 +1,33 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.htl.checks; + +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; + +class PlaceTemplatesInSeparateFilesCheckTest extends AbstractBaseTest { + + @Test + void checkHtlAttributesOrder() { + this.check = new PlaceTemplatesInSeparateFilesCheck(); + this.filename = "src/test/files/htl/PlaceTemplatesInSeparateFilesCheck.html"; + verify(); + } +} diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/UseSlyTagsOverRedundantMarkupCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/SlyElementsAreAutomaticallyUnwrappedCheckTest.java similarity index 61% rename from src/test/java/com/cognifide/aemrules/htl/checks/UseSlyTagsOverRedundantMarkupCheckTest.java rename to src/test/java/com/vml/aemrules/htl/checks/SlyElementsAreAutomaticallyUnwrappedCheckTest.java index 62fc2ace..397cd228 100644 --- a/src/test/java/com/cognifide/aemrules/htl/checks/UseSlyTagsOverRedundantMarkupCheckTest.java +++ b/src/test/java/com/vml/aemrules/htl/checks/SlyElementsAreAutomaticallyUnwrappedCheckTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,17 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; -public class UseSlyTagsOverRedundantMarkupCheckTest extends AbstractBaseTest { +class SlyElementsAreAutomaticallyUnwrappedCheckTest extends AbstractBaseTest { @Test - public void checkRedundantSlyTags() { - check = new UseSlyTagsOverRedundantMarkupCheck(); - filename = "src/test/files/checks/htl/UseSlyTagsOverRedundantMarkupCheck.html"; + void checkRedundantUnwrapAttributes() { + this.check = new SlyElementsAreAutomaticallyUnwrappedCheck(); + this.filename = "src/test/files/htl/SlyElementsAreAutomaticallyUnwrappedCheck.html"; verify(); } } diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/DefaultDisplayContextCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/UseMostRestrictiveHtlContextCheckTest.java similarity index 61% rename from src/test/java/com/cognifide/aemrules/htl/checks/DefaultDisplayContextCheckTest.java rename to src/test/java/com/vml/aemrules/htl/checks/UseMostRestrictiveHtlContextCheckTest.java index c5dd1d08..c38fdc58 100644 --- a/src/test/java/com/cognifide/aemrules/htl/checks/DefaultDisplayContextCheckTest.java +++ b/src/test/java/com/vml/aemrules/htl/checks/UseMostRestrictiveHtlContextCheckTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,17 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; -public class DefaultDisplayContextCheckTest extends AbstractBaseTest { +class UseMostRestrictiveHtlContextCheckTest extends AbstractBaseTest { @Test - public void checkDefaultDisplayContext() { - check = new DefaultDisplayContextCheck(); - filename = "src/test/files/checks/htl/UseDefaultDisplayContextCheck.html"; + void checkAllDataAttributesContainsDisplayContext() { + this.check = new UseMostRestrictiveHtlContextCheck(); + this.filename = "src/test/files/htl/UseMostRestrictiveHtlContextCheck.html"; verify(); } } diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/AvoidExtraSlyTagsCheckTest.java b/src/test/java/com/vml/aemrules/htl/checks/UseSlyTagsOverRedundantMarkupCheckTest.java similarity index 61% rename from src/test/java/com/cognifide/aemrules/htl/checks/AvoidExtraSlyTagsCheckTest.java rename to src/test/java/com/vml/aemrules/htl/checks/UseSlyTagsOverRedundantMarkupCheckTest.java index b4231a1f..f52cdc7a 100644 --- a/src/test/java/com/cognifide/aemrules/htl/checks/AvoidExtraSlyTagsCheckTest.java +++ b/src/test/java/com/vml/aemrules/htl/checks/UseSlyTagsOverRedundantMarkupCheckTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,17 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.htl.checks; -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; +import com.vml.aemrules.htl.AbstractBaseTest; +import org.junit.jupiter.api.Test; -public class AvoidExtraSlyTagsCheckTest extends AbstractBaseTest { +class UseSlyTagsOverRedundantMarkupCheckTest extends AbstractBaseTest { @Test - public void avoidExtraSlyTags() { - check = new AvoidExtraSlyTagsCheck(); - filename = "src/test/files/checks/htl/AvoidExtraSlyTagsCheck.html"; + void checkRedundantSlyTags() { + this.check = new UseSlyTagsOverRedundantMarkupCheck(); + this.filename = "src/test/files/htl/UseSlyTagsOverRedundantMarkupCheck.html"; verify(); } } diff --git a/src/test/java/com/cognifide/aemrules/htl/visitors/HtlNodeCounterVisitor.java b/src/test/java/com/vml/aemrules/htl/visitors/HtlNodeCounterVisitor.java similarity index 95% rename from src/test/java/com/cognifide/aemrules/htl/visitors/HtlNodeCounterVisitor.java rename to src/test/java/com/vml/aemrules/htl/visitors/HtlNodeCounterVisitor.java index 94509b5e..05a0ef8e 100644 --- a/src/test/java/com/cognifide/aemrules/htl/visitors/HtlNodeCounterVisitor.java +++ b/src/test/java/com/vml/aemrules/htl/visitors/HtlNodeCounterVisitor.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,8 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.visitors; +package com.vml.aemrules.htl.visitors; -import java.util.HashMap; -import java.util.List; -import java.util.Map; import org.apache.sling.scripting.sightly.compiler.expression.Expression; import org.sonar.plugins.html.node.CommentNode; import org.sonar.plugins.html.node.DirectiveNode; @@ -31,11 +28,15 @@ import org.sonar.plugins.html.node.TextNode; import org.sonar.plugins.html.visitor.HtmlSourceCode; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + public class HtlNodeCounterVisitor implements DefaultHtlVisitor { private HtmlSourceCode sourceCode = null; - private Map counterMap; + private final Map counterMap; public HtlNodeCounterVisitor() { counterMap = new HashMap<>(); diff --git a/src/test/java/com/cognifide/aemrules/htl/visitors/HtlScannerTest.java b/src/test/java/com/vml/aemrules/htl/visitors/HtlScannerTest.java similarity index 80% rename from src/test/java/com/cognifide/aemrules/htl/visitors/HtlScannerTest.java rename to src/test/java/com/vml/aemrules/htl/visitors/HtlScannerTest.java index 80e7a33b..01f51dfd 100644 --- a/src/test/java/com/cognifide/aemrules/htl/visitors/HtlScannerTest.java +++ b/src/test/java/com/vml/aemrules/htl/visitors/HtlScannerTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,21 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.visitors; +package com.vml.aemrules.htl.visitors; -import static org.junit.Assert.assertEquals; +import com.google.common.io.Files; +import com.vml.aemrules.htl.Htl; +import com.vml.aemrules.htl.lex.HtlLexer; +import com.vml.aemrules.utils.Throwables; +import org.apache.sling.scripting.sightly.compiler.expression.Expression; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.sonar.api.batch.fs.internal.TestInputFileBuilder; +import org.sonar.plugins.html.node.CommentNode; +import org.sonar.plugins.html.node.Node; +import org.sonar.plugins.html.node.TagNode; +import org.sonar.plugins.html.visitor.HtmlSourceCode; -import com.cognifide.aemrules.htl.lex.HtlLexer; import java.io.File; import java.io.IOException; import java.io.Reader; @@ -29,19 +39,9 @@ import java.nio.charset.StandardCharsets; import java.util.List; -import com.cognifide.aemrules.utils.Throwables; -import org.apache.sling.scripting.sightly.compiler.expression.Expression; -import org.junit.Before; -import org.junit.Test; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import com.google.common.io.Files; -import org.sonar.plugins.html.api.HtmlConstants; -import org.sonar.plugins.html.node.CommentNode; -import org.sonar.plugins.html.node.Node; -import org.sonar.plugins.html.node.TagNode; -import org.sonar.plugins.html.visitor.HtmlSourceCode; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class HtlScannerTest { +class HtlScannerTest { private HtlNodeCounterVisitor counterVisitor; @@ -49,7 +49,7 @@ public class HtlScannerTest { private HtlLexer lexer; - @Before + @BeforeEach public void setUp() { lexer = new HtlLexer(); htlScanner = new HtlScanner(); @@ -58,7 +58,7 @@ public void setUp() { } @Test - public void checkVisitedNode() { + void checkVisitedNode() { HtmlSourceCode htmlSourceCode = createHtmlSourceCode("scanner/testFile.html"); try (Reader reader = readFile("scanner/testFile.html")) { List nodes = lexer.parse(reader); @@ -73,9 +73,9 @@ public void checkVisitedNode() { private HtmlSourceCode createHtmlSourceCode(String relativePath) { return new HtmlSourceCode(new TestInputFileBuilder("key", relativePath) - .setLanguage(HtmlConstants.LANGUAGE_KEY) - .setModuleBaseDir(new File(".").toPath()) - .build() + .setLanguage(Htl.LANGUAGE_KEY) + .setModuleBaseDir(new File(".").toPath()) + .build() ); } @@ -83,9 +83,9 @@ private Reader readFile(String fileName) { File root = new File("src/test/resources"); File file = new File(root, fileName); try { - return new StringReader(Files.toString(file, StandardCharsets.UTF_8)); + return new StringReader(Files.asCharSource(file, StandardCharsets.UTF_8).read()); } catch (IOException e) { throw new IllegalArgumentException("Cannot read " + fileName, e); } } -} \ No newline at end of file +} diff --git a/src/test/java/com/cognifide/aemrules/java/checks/AbstractBaseTest.java b/src/test/java/com/vml/aemrules/java/checks/AbstractBaseTest.java similarity index 96% rename from src/test/java/com/cognifide/aemrules/java/checks/AbstractBaseTest.java rename to src/test/java/com/vml/aemrules/java/checks/AbstractBaseTest.java index 5f997fed..708426c6 100644 --- a/src/test/java/com/cognifide/aemrules/java/checks/AbstractBaseTest.java +++ b/src/test/java/com/vml/aemrules/java/checks/AbstractBaseTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,16 +17,16 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; +package com.vml.aemrules.java.checks; import org.apache.commons.lang3.StringUtils; import org.sonar.java.checks.verifier.CheckVerifier; import org.sonar.plugins.java.api.JavaFileScanner; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + public abstract class AbstractBaseTest { /** diff --git a/src/test/java/com/cognifide/aemrules/java/checks/AdministrativeAccessUsageCheckTest.java b/src/test/java/com/vml/aemrules/java/checks/AdministrativeAccessUsageCheckTest.java similarity index 62% rename from src/test/java/com/cognifide/aemrules/java/checks/AdministrativeAccessUsageCheckTest.java rename to src/test/java/com/vml/aemrules/java/checks/AdministrativeAccessUsageCheckTest.java index 861a7304..3d65f8d4 100644 --- a/src/test/java/com/cognifide/aemrules/java/checks/AdministrativeAccessUsageCheckTest.java +++ b/src/test/java/com/vml/aemrules/java/checks/AdministrativeAccessUsageCheckTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,16 +17,16 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; +package com.vml.aemrules.java.checks; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class AdministrativeAccessUsageCheckTest extends AbstractBaseTest { +class AdministrativeAccessUsageCheckTest extends AbstractBaseTest { @Test - public void administrativeAccessUsageCheck() { - check = new AdministrativeAccessUsageCheck(); - filename = "src/test/files/checks/java/AdministrativeAccessUsageCheck.java"; + void administrativeAccessUsageCheck() { + this.check = new AdministrativeAccessUsageCheck(); + this.filename = "src/test/files/java/AdministrativeAccessUsageCheck.java"; verify(); } diff --git a/src/test/java/com/cognifide/aemrules/java/checks/AnnotationsConstantsCheckTest.java b/src/test/java/com/vml/aemrules/java/checks/AnnotationsConstantsCheckTest.java similarity index 64% rename from src/test/java/com/cognifide/aemrules/java/checks/AnnotationsConstantsCheckTest.java rename to src/test/java/com/vml/aemrules/java/checks/AnnotationsConstantsCheckTest.java index 11086eb1..902f6524 100644 --- a/src/test/java/com/cognifide/aemrules/java/checks/AnnotationsConstantsCheckTest.java +++ b/src/test/java/com/vml/aemrules/java/checks/AnnotationsConstantsCheckTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,16 +17,16 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; +package com.vml.aemrules.java.checks; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class AnnotationsConstantsCheckTest extends AbstractBaseTest { +class AnnotationsConstantsCheckTest extends AbstractBaseTest { @Test - public void checkConstantsInAnnotations() { - check = new AnnotationsConstantsCheck(); - filename = "src/test/files/checks/java/AnnotationsConstantsCheck.java"; + void checkConstantsInAnnotations() { + this.check = new AnnotationsConstantsCheck(); + this.filename = "src/test/files/java/AnnotationsConstantsCheck.java"; verify(false); } diff --git a/src/test/java/com/cognifide/aemrules/java/checks/ConstantsCheckTest.java b/src/test/java/com/vml/aemrules/java/checks/ConstantsCheckTest.java similarity index 67% rename from src/test/java/com/cognifide/aemrules/java/checks/ConstantsCheckTest.java rename to src/test/java/com/vml/aemrules/java/checks/ConstantsCheckTest.java index 56b3725a..c81b55f1 100644 --- a/src/test/java/com/cognifide/aemrules/java/checks/ConstantsCheckTest.java +++ b/src/test/java/com/vml/aemrules/java/checks/ConstantsCheckTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,16 +17,16 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; +package com.vml.aemrules.java.checks; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ConstantsCheckTest extends AbstractBaseTest { +class ConstantsCheckTest extends AbstractBaseTest { @Test - public void checkConstants() { - check = new ConstantsCheck(); - filename = "src/test/files/checks/java/ConstantsCheck.java"; + void checkConstants() { + this.check = new ConstantsCheck(); + this.filename = "src/test/files/java/ConstantsCheck.java"; verify(false); } } diff --git a/src/test/java/com/vml/aemrules/java/checks/ContentResourceShouldBeNullCheckedCheckTest.java b/src/test/java/com/vml/aemrules/java/checks/ContentResourceShouldBeNullCheckedCheckTest.java new file mode 100644 index 00000000..ff6cf966 --- /dev/null +++ b/src/test/java/com/vml/aemrules/java/checks/ContentResourceShouldBeNullCheckedCheckTest.java @@ -0,0 +1,32 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.java.checks; + +import org.junit.jupiter.api.Test; + +class ContentResourceShouldBeNullCheckedCheckTest extends AbstractBaseTest { + + @Test + void checkIfContentResourceIsNotNull() { + this.check = new ContentResourceShouldBeNullCheckedCheck(); + this.filename = "src/test/files/java/ContentResourceShouldBeNullCheckedCheck.java"; + verify(); + } +} diff --git a/src/test/java/com/vml/aemrules/java/checks/DefaultInjectionStrategyAnnotationCheckTest.java b/src/test/java/com/vml/aemrules/java/checks/DefaultInjectionStrategyAnnotationCheckTest.java new file mode 100644 index 00000000..54ade811 --- /dev/null +++ b/src/test/java/com/vml/aemrules/java/checks/DefaultInjectionStrategyAnnotationCheckTest.java @@ -0,0 +1,41 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.java.checks; + +import com.vml.aemrules.java.checks.slingmodels.DefaultInjectionStrategyAnnotationCheck; +import org.junit.jupiter.api.Test; + +class DefaultInjectionStrategyAnnotationCheckTest extends AbstractBaseTest { + + @Test + void checkAnnotation() { + this.check = new DefaultInjectionStrategyAnnotationCheck(); + this.filename = "src/test/files/java/DefaultInjectionStrategyAnnotationCheck.java"; + verify(); + } + + @Test + void checkMultipleAdaptablesAnnotation() { + this.check = new DefaultInjectionStrategyAnnotationCheck(); + this.filename = "src/test/files/java/DefaultInjectionStrategyAnnotationCheckMultipleAdaptables.java"; + verify(); + } + +} diff --git a/src/test/java/com/vml/aemrules/java/checks/ModifiableValueMapUsageCheckTest.java b/src/test/java/com/vml/aemrules/java/checks/ModifiableValueMapUsageCheckTest.java new file mode 100644 index 00000000..86bd53f4 --- /dev/null +++ b/src/test/java/com/vml/aemrules/java/checks/ModifiableValueMapUsageCheckTest.java @@ -0,0 +1,32 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.java.checks; + +import org.junit.jupiter.api.Test; + +class ModifiableValueMapUsageCheckTest extends AbstractBaseTest { + + @Test + void checkIfMVMIsUsedToRetrievePropertiesFromResource() { + this.check = new ModifiableValueMapUsageCheck(); + this.filename = "src/test/files/java/ModifiableValueMapUsageCheck.java"; + verify(); + } +} diff --git a/src/test/java/com/vml/aemrules/java/checks/PreferSlingServletAnnotationTest.java b/src/test/java/com/vml/aemrules/java/checks/PreferSlingServletAnnotationTest.java new file mode 100644 index 00000000..7a29f580 --- /dev/null +++ b/src/test/java/com/vml/aemrules/java/checks/PreferSlingServletAnnotationTest.java @@ -0,0 +1,48 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.java.checks; + + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class PreferSlingServletAnnotationTest extends AbstractBaseTest { + + @ParameterizedTest + @CsvSource({ + "checkLackOfAnnotation,src/test/files/java/SlingServletOne.java", + "checkMixedAnnotations,src/test/files/java/SlingServletTwo.java", + "checkRedundantProperties,src/test/files/java/SlingServletThree.java" + }) + void detect(String description, String fileName) { + System.out.println(description); + this.check = new PreferSlingServletAnnotation(); + this.filename = fileName; + verify(); + } + + @Test + void checkStandardAnnotations() { + this.check = new PreferSlingServletAnnotation(); + this.filename = "src/test/files/java/SlingServletWithStandardAnnotations.java"; + verifyNoIssues(); + } +} diff --git a/src/test/java/com/vml/aemrules/java/checks/ResourceResolverShouldBeClosedTest.java b/src/test/java/com/vml/aemrules/java/checks/ResourceResolverShouldBeClosedTest.java new file mode 100644 index 00000000..ae964962 --- /dev/null +++ b/src/test/java/com/vml/aemrules/java/checks/ResourceResolverShouldBeClosedTest.java @@ -0,0 +1,53 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.java.checks; + +import com.vml.aemrules.java.checks.resourceresolver.close.ResourceResolverShouldBeClosed; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class ResourceResolverShouldBeClosedTest extends AbstractBaseTest { + + @ParameterizedTest + @CsvSource({ + "checkInjectorNotClosedInFinallyBlock,src/test/files/java/SampleServlet.java", + "checkResourceResolverClosedInDeactivateMethodError,src/test/files/java/LongResourceResolverEvenListenerError.java" + }) + void detect_1(String description, String fileName) { + System.out.println(description); + this.check = new ResourceResolverShouldBeClosed(); + this.filename = fileName; + verify(); + } + + @ParameterizedTest + @CsvSource({ + "checkResourceResolverNotClosedInFinallyBlockWhenResourceResolverComesFromDifferentClass,src/test/files/java/ResourceResolverConsumer.java", + "checkResourceResolverNotClosedWhenItIsOpenedInActivateAndClosedInDeactivate,src/test/files/java/LongSessionService.java", + "checkResourceResolverClosedInDeactivateMethod,src/test/files/java/LongSessionEventListener.java" + }) + void detect_2(String description, String fileName) { + System.out.println(description); + this.check = new ResourceResolverShouldBeClosed(); + this.filename = fileName; + verifyNoIssues(); + } + +} diff --git a/src/test/java/com/cognifide/aemrules/htl/checks/DisplayContextInConditionalCommentsCheckTest.java b/src/test/java/com/vml/aemrules/java/checks/ResourceResolverTryWithResourcesTest.java similarity index 57% rename from src/test/java/com/cognifide/aemrules/htl/checks/DisplayContextInConditionalCommentsCheckTest.java rename to src/test/java/com/vml/aemrules/java/checks/ResourceResolverTryWithResourcesTest.java index 461f3a47..b02d7849 100644 --- a/src/test/java/com/cognifide/aemrules/htl/checks/DisplayContextInConditionalCommentsCheckTest.java +++ b/src/test/java/com/vml/aemrules/java/checks/ResourceResolverTryWithResourcesTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,18 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.htl.checks; +package com.vml.aemrules.java.checks; -import com.cognifide.aemrules.htl.AbstractBaseTest; -import org.junit.Test; +import com.vml.aemrules.java.checks.resourceresolver.close.ResourceResolverTryWithResourcesCheck; +import org.junit.jupiter.api.Test; -public class DisplayContextInConditionalCommentsCheckTest extends AbstractBaseTest { +class ResourceResolverTryWithResourcesTest extends AbstractBaseTest { @Test - public void checkContextInConditionalComments() { - check = new DisplayContextInConditionalCommentsCheck(); - filename = "src/test/files/checks/htl/DisplayContextInConditionalCommentsCheck.html"; + void checkResourceResolverUsesTryWithResourcesBlock() { + this.check = new ResourceResolverTryWithResourcesCheck(); + this.filename = "src/test/files/java/AutoclosableResourceResolver.java"; verify(); } + } diff --git a/src/test/java/com/vml/aemrules/java/checks/SessionShouldBeLoggedOutTest.java b/src/test/java/com/vml/aemrules/java/checks/SessionShouldBeLoggedOutTest.java new file mode 100644 index 00000000..79ce8d64 --- /dev/null +++ b/src/test/java/com/vml/aemrules/java/checks/SessionShouldBeLoggedOutTest.java @@ -0,0 +1,49 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.java.checks; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class SessionShouldBeLoggedOutTest extends AbstractBaseTest { + + @ParameterizedTest + @CsvSource({ + "src/test/files/java/SessionLogoutOne.java,false", + "src/test/files/java/SessionLogoutTwo.java,false", + "src/test/files/java/SessionLogoutThree.java,false", + "src/test/files/java/SessionLogoutFour.java,true", + "src/test/files/java/SessionLogoutFive.java,true", + "src/test/files/java/SessionLogoutSix.java,true", + "src/test/files/java/SessionLogoutSeven.java,true", + "src/test/files/java/SessionLogoutEight.java,false", + "src/test/files/java/LongSessionEventListener.java,false", + "src/test/files/java/LongSessionEventListenerError.java,true" + }) + void checkInjectorNotClosedInFinallyBlock(String fileName, boolean expectFailure) { + this.filename = fileName; + this.check = new SessionShouldBeLoggedOut(); + if (expectFailure) { + verify(); + } else { + verifyNoIssues(); + } + } +} diff --git a/src/test/java/com/vml/aemrules/java/checks/SlingQueryImplicitStrategyCheckTest.java b/src/test/java/com/vml/aemrules/java/checks/SlingQueryImplicitStrategyCheckTest.java new file mode 100644 index 00000000..2876d0c7 --- /dev/null +++ b/src/test/java/com/vml/aemrules/java/checks/SlingQueryImplicitStrategyCheckTest.java @@ -0,0 +1,34 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.java.checks; + +import com.vml.aemrules.java.checks.slingquery.SlingQueryImplicitStrategyCheck; +import org.junit.jupiter.api.Test; + +class SlingQueryImplicitStrategyCheckTest extends AbstractBaseTest { + + @Test + void checkImplicitSearches() { + this.check = new SlingQueryImplicitStrategyCheck(); + this.filename = "src/test/files/java/SlingQueryImplicitStrategyCheck.java"; + verify(); + } + +} diff --git a/src/test/java/com/cognifide/aemrules/java/checks/SynchronizedKeywordUsageCheckTest.java b/src/test/java/com/vml/aemrules/java/checks/SynchronizedKeywordUsageCheckTest.java similarity index 62% rename from src/test/java/com/cognifide/aemrules/java/checks/SynchronizedKeywordUsageCheckTest.java rename to src/test/java/com/vml/aemrules/java/checks/SynchronizedKeywordUsageCheckTest.java index dddbecf9..1acb43d4 100644 --- a/src/test/java/com/cognifide/aemrules/java/checks/SynchronizedKeywordUsageCheckTest.java +++ b/src/test/java/com/vml/aemrules/java/checks/SynchronizedKeywordUsageCheckTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,16 +17,16 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.java.checks; +package com.vml.aemrules.java.checks; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class SynchronizedKeywordUsageCheckTest extends AbstractBaseTest { +class SynchronizedKeywordUsageCheckTest extends AbstractBaseTest { @Test - public void checkThreadSafeFieldsInServlet() { - check = new SynchronizedKeywordUsageCheck(); - filename = "src/test/files/checks/java/SynchronizedKeywordUsageCheck.java"; + void checkThreadSafeFieldsInServlet() { + this.check = new SynchronizedKeywordUsageCheck(); + this.filename = "src/test/files/java/SynchronizedKeywordUsageCheck.java"; verify(); } diff --git a/src/test/java/com/vml/aemrules/java/checks/ThreadSafeFieldCheckTest.java b/src/test/java/com/vml/aemrules/java/checks/ThreadSafeFieldCheckTest.java new file mode 100644 index 00000000..bcdffe91 --- /dev/null +++ b/src/test/java/com/vml/aemrules/java/checks/ThreadSafeFieldCheckTest.java @@ -0,0 +1,42 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.java.checks; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class ThreadSafeFieldCheckTest extends AbstractBaseTest { + + @ParameterizedTest + @CsvSource({ + "checkThreadSafeFieldsInServlet,src/test/files/java/ThreadSafeFieldCheckServlet.java", + "checkThreadSafeFieldsInFilter,src/test/files/java/ThreadSafeFieldCheckFilter.java", + "checkThreadSafeFieldsInEventHandler,src/test/files/java/ThreadSafeFieldCheckEventHandler.java", + "checkThreadSafeFieldsInScrComponent,src/test/files/java/ThreadSafeFieldCheckScrComponentAnnotation.java", + "checkThreadSafeFieldsInDsComponent,src/test/files/java/ThreadSafeFieldCheckDsComponentAnnotation.java", + "checkThreadSafeFieldsInSlingServletAnnotated,src/test/files/java/ThreadSafeFieldCheckSlingServletAnnotation.java" + }) + void detect(String description, String fileName) { + System.out.println(description); + this.check = new ThreadSafeFieldCheck(); + this.filename = fileName; + verify(); + } +} diff --git a/src/test/java/com/cognifide/aemrules/matcher/MethodMatcherTest.java b/src/test/java/com/vml/aemrules/matcher/MethodMatcherTest.java similarity index 52% rename from src/test/java/com/cognifide/aemrules/matcher/MethodMatcherTest.java rename to src/test/java/com/vml/aemrules/matcher/MethodMatcherTest.java index 53ff84f8..e6250071 100644 --- a/src/test/java/com/cognifide/aemrules/matcher/MethodMatcherTest.java +++ b/src/test/java/com/vml/aemrules/matcher/MethodMatcherTest.java @@ -2,7 +2,7 @@ * #%L * AEM Rules for SonarQube * %% - * Copyright (C) 2015-2019 Wunderman Thompson Technology + * Copyright (C) 2015-2024 VML * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,12 @@ * limitations under the License. * #L% */ -package com.cognifide.aemrules.matcher; +package com.vml.aemrules.matcher; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.sonar.java.model.JParser; import org.sonar.java.model.JParserConfig; +import org.sonar.java.model.JavaVersionImpl; import org.sonar.plugins.java.api.tree.ClassTree; import org.sonar.plugins.java.api.tree.CompilationUnitTree; import org.sonar.plugins.java.api.tree.ExpressionStatementTree; @@ -35,122 +35,114 @@ import java.util.List; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; public class MethodMatcherTest { - private static final String CODE_TO_PARSE_METHOD_SELECT_KIND_IDENTIFIER = "package com.cognifide.test; " - + "class MyClass1 {}" - + "class MyClass2 {}" - + "class TestClass { " - + "void test(MyClass1 m1, MyClass2 m2){}" - + "void bar(){MyClass1 m1 = new MyClass1(); MyClass2 m2 = new MyClass2(); test(m1, m2);} " - + "}"; - - private static final String CODE_TO_PARSE_METHOD_SELECT_KIND_MEMBER_SELECT = "package com.cognifide.test; " - + "class MyClass1 {}" - + "class MyClass2 {}" - + "class TestClass { " - + "void test(MyClass1 m1, MyClass2 m2){}" - + "void bar(){MyClass1 m1 = new MyClass1(); MyClass2 m2 = new MyClass2(); this.test(m1, m2);} " - + "}"; - - private static final int CLASS_INDEX = 2; - - private static final int CLASS_METHOD_INDEX = 1; - - private static final int METHOD_INVOCATION_INDEX = 2; - public static final String CLASSES_FILEPATH = "target/classes"; - public static final String TEST_CLASSES_FILEPATH = "target/test-classes"; - public static final String JAVA_VERSION = "1.8"; - public static final String UNIT_NAME = "test"; - + private static final String CODE_TO_PARSE_METHOD_SELECT_KIND_IDENTIFIER = "package com.vml.test; " + + "class MyClass1 {}" + + "class MyClass2 {}" + + "class TestClass { " + + "void test(MyClass1 m1, MyClass2 m2){}" + + "void bar(){MyClass1 m1 = new MyClass1(); MyClass2 m2 = new MyClass2(); test(m1, m2);} " + + "}"; + private static final String CODE_TO_PARSE_METHOD_SELECT_KIND_MEMBER_SELECT = "package com.vml.test; " + + "class MyClass1 {}" + + "class MyClass2 {}" + + "class TestClass { " + + "void test(MyClass1 m1, MyClass2 m2){}" + + "void bar(){MyClass1 m1 = new MyClass1(); MyClass2 m2 = new MyClass2(); this.test(m1, m2);} " + + "}"; + private static final int CLASS_INDEX = 2; + private static final int CLASS_METHOD_INDEX = 1; + private static final int METHOD_INVOCATION_INDEX = 2; private MethodInvocationTree methodInvocationTree; @Test - public void shouldMatchMethodWhenMethodNameAndOwnerClassAndMethodParametersMatch() { + void shouldMatchMethodWhenMethodNameAndOwnerClassAndMethodParametersMatch() { givenMethodInvocationTree(CODE_TO_PARSE_METHOD_SELECT_KIND_IDENTIFIER); MethodMatcher methodMatcher = MethodMatcher.create( - MethodNamePredicate.is(UNIT_NAME), - OwnerTypePredicate.is("com.cognifide.test.TestClass"), - ParameterTypePredicate.is("com.cognifide.test.MyClass1"), - ParameterTypePredicate.is("com.cognifide.test.MyClass2") + MethodNamePredicate.is(UNIT_NAME), + OwnerTypePredicate.is("com.vml.test.TestClass"), + ParameterTypePredicate.is("com.vml.test.MyClass1"), + ParameterTypePredicate.is("com.vml.test.MyClass2") ); - Assert.assertThat(methodMatcher.matches(methodInvocationTree), is(true)); + assertThat(methodMatcher.matches(methodInvocationTree), is(true)); } @Test - public void shouldMatchMethodWhenMethodNameAndOwnerClassAndOnlySecondParameterMatch() { + void shouldMatchMethodWhenMethodNameAndOwnerClassAndOnlySecondParameterMatch() { givenMethodInvocationTree(CODE_TO_PARSE_METHOD_SELECT_KIND_MEMBER_SELECT); MethodMatcher methodMatcher = MethodMatcher.create( - MethodNamePredicate.is(UNIT_NAME), - OwnerTypePredicate.is("com.cognifide.test.TestClass"), - ParameterTypePredicate.anyParameterType(), - ParameterTypePredicate.is("com.cognifide.test.MyClass2") + MethodNamePredicate.is(UNIT_NAME), + OwnerTypePredicate.is("com.vml.test.TestClass"), + ParameterTypePredicate.anyParameterType(), + ParameterTypePredicate.is("com.vml.test.MyClass2") ); - Assert.assertThat(methodMatcher.matches(methodInvocationTree), is(true)); + assertThat(methodMatcher.matches(methodInvocationTree), is(true)); } @Test - public void shouldNotMatchMethodWhenMethodNameDoesNotMatch() { + void shouldNotMatchMethodWhenMethodNameDoesNotMatch() { givenMethodInvocationTree(CODE_TO_PARSE_METHOD_SELECT_KIND_IDENTIFIER); MethodMatcher methodMatcher = MethodMatcher.create( - MethodNamePredicate.is("different"), - OwnerTypePredicate.is("com.cognifide.test.TestClass"), - ParameterTypePredicate.is("com.cognifide.test.MyClass1"), - ParameterTypePredicate.is("com.cognifide.test.MyClass2") + MethodNamePredicate.is("different"), + OwnerTypePredicate.is("com.vml.test.TestClass"), + ParameterTypePredicate.is("com.vml.test.MyClass1"), + ParameterTypePredicate.is("com.vml.test.MyClass2") ); - Assert.assertThat(methodMatcher.matches(methodInvocationTree), is(false)); + assertThat(methodMatcher.matches(methodInvocationTree), is(false)); } @Test - public void shouldNotMatchMethodWhenNumberOfMethodParametersDoesNotMatch() { + void shouldNotMatchMethodWhenNumberOfMethodParametersDoesNotMatch() { givenMethodInvocationTree(CODE_TO_PARSE_METHOD_SELECT_KIND_MEMBER_SELECT); MethodMatcher methodMatcher = MethodMatcher.create( - MethodNamePredicate.is(UNIT_NAME), - OwnerTypePredicate.is("com.cognifide.test.TestClass"), - ParameterTypePredicate.is("com.cognifide.test.MyClass1") + MethodNamePredicate.is(UNIT_NAME), + OwnerTypePredicate.is("com.vml.test.TestClass"), + ParameterTypePredicate.is("com.vml.test.MyClass1") ); - Assert.assertThat(methodMatcher.matches(methodInvocationTree), is(false)); + assertThat(methodMatcher.matches(methodInvocationTree), is(false)); } @Test - public void shouldNotMatchMethodWhenMethodOwnerClassDoesNotMatch() { + void shouldNotMatchMethodWhenMethodOwnerClassDoesNotMatch() { givenMethodInvocationTree(CODE_TO_PARSE_METHOD_SELECT_KIND_IDENTIFIER); MethodMatcher methodMatcher = MethodMatcher.create( - MethodNamePredicate.is(UNIT_NAME), - OwnerTypePredicate.is("com.cognifide.test.Different"), - ParameterTypePredicate.is("com.cognifide.test.MyClass1"), - ParameterTypePredicate.is("com.cognifide.test.MyClass2") + MethodNamePredicate.is(UNIT_NAME), + OwnerTypePredicate.is("com.vml.test.Different"), + ParameterTypePredicate.is("com.vml.test.MyClass1"), + ParameterTypePredicate.is("com.vml.test.MyClass2") ); - Assert.assertThat(methodMatcher.matches(methodInvocationTree), is(false)); + assertThat(methodMatcher.matches(methodInvocationTree), is(false)); } @Test - public void shouldNotMatchMethodWhenMethodParameterTypesDoNotMatch() { + void shouldNotMatchMethodWhenMethodParameterTypesDoNotMatch() { givenMethodInvocationTree(CODE_TO_PARSE_METHOD_SELECT_KIND_MEMBER_SELECT); MethodMatcher methodMatcher = MethodMatcher.create( - MethodNamePredicate.is(UNIT_NAME), - OwnerTypePredicate.is("com.cognifide.test.TestClass"), - ParameterTypePredicate.is("com.cognifide.test.Different1"), - ParameterTypePredicate.is("com.cognifide.test.MyClass2") + MethodNamePredicate.is(UNIT_NAME), + OwnerTypePredicate.is("com.vml.test.TestClass"), + ParameterTypePredicate.is("com.vml.test.Different1"), + ParameterTypePredicate.is("com.vml.test.MyClass2") ); - Assert.assertThat(methodMatcher.matches(methodInvocationTree), is(false)); + assertThat(methodMatcher.matches(methodInvocationTree), is(false)); } private void givenMethodInvocationTree(String codeToParse) { @@ -162,8 +154,7 @@ private void givenMethodInvocationTree(String codeToParse) { private CompilationUnitTree parse(String source) { List classpath = Arrays.asList(new File(TEST_CLASSES_FILEPATH), new File(CLASSES_FILEPATH)); - return JParser.parse(JParserConfig.Mode.FILE_BY_FILE.create(JAVA_VERSION, classpath).astParser(), JAVA_VERSION, UNIT_NAME, source); + return JParser.parse(JParserConfig.Mode.FILE_BY_FILE.create(new JavaVersionImpl(11), classpath).astParser(), JAVA_VERSION, UNIT_NAME, source); } } - diff --git a/src/test/java/com/vml/aemrules/version/VersionSupportCheckerTest.java b/src/test/java/com/vml/aemrules/version/VersionSupportCheckerTest.java new file mode 100644 index 00000000..5c709283 --- /dev/null +++ b/src/test/java/com/vml/aemrules/version/VersionSupportCheckerTest.java @@ -0,0 +1,190 @@ +/*- + * #%L + * AEM Rules for SonarQube + * %% + * Copyright (C) 2015-2024 VML + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.vml.aemrules.version; + +import org.junit.jupiter.api.Test; + +import static com.vml.aemrules.version.VersionSupportChecker.DEFAULT_AEM_VERSION; +import static com.vml.aemrules.version.VersionSupportChecker.create; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class VersionSupportCheckerTest { + + @Test + void shouldSupportAllVersionsWhenAllSet() { + VersionSupportChecker versionSupportChecker = create( + CheckSupportingAllVersions.class.getAnnotation(AemVersion.class)); + assertThat(versionSupportChecker.supports("6.3"), is(true)); + assertThat(versionSupportChecker.supports("2.1"), is(true)); + assertThat(versionSupportChecker.supports("2.0"), is(true)); + } + + @Test + void shouldSupportAllVersionsBetweenFromAndTo() { + VersionSupportChecker versionSupportChecker = create( + CheckSupportingVersionsFromTo.class.getAnnotation(AemVersion.class)); + assertThat(versionSupportChecker.supports("6.1"), is(true)); + assertThat(versionSupportChecker.supports("5.2"), is(true)); + assertThat(versionSupportChecker.supports("5.1"), is(true)); + assertThat(versionSupportChecker.supports("6.4"), is(true)); + assertThat(versionSupportChecker.supports("6.5"), is(false)); + assertThat(versionSupportChecker.supports("5.0"), is(false)); + } + + @Test + void shouldSupportAllVersionsFrom() { + VersionSupportChecker versionSupportChecker = create( + CheckSupportingVersionsFrom.class.getAnnotation(AemVersion.class)); + assertThat(versionSupportChecker.supports("100.1"), is(true)); + assertThat(versionSupportChecker.supports("10.1"), is(true)); + assertThat(versionSupportChecker.supports("17.2"), is(true)); + assertThat(versionSupportChecker.supports("10.0"), is(false)); + assertThat(versionSupportChecker.supports("5.9"), is(false)); + } + + @Test + void shouldSupportAllVersionsTo() { + VersionSupportChecker supportedVersions = create( + CheckSupportingVersionsTo.class.getAnnotation(AemVersion.class)); + assertThat(supportedVersions.supports("1.1"), is(true)); + assertThat(supportedVersions.supports("10.1"), is(true)); + assertThat(supportedVersions.supports("0.2"), is(true)); + assertThat(supportedVersions.supports("8.5"), is(true)); + assertThat(supportedVersions.supports("10.2"), is(false)); + assertThat(supportedVersions.supports("20.9"), is(false)); + } + + @Test + void shouldSupportAllProvidedVersions() { + VersionSupportChecker supportedVersions = create( + CheckSupportingVersionsIncluded.class.getAnnotation(AemVersion.class)); + assertThat(supportedVersions.supports("6.1"), is(true)); + assertThat(supportedVersions.supports("2.1"), is(true)); + assertThat(supportedVersions.supports("4.8"), is(true)); + assertThat(supportedVersions.supports("6.0"), is(false)); + assertThat(supportedVersions.supports("2.2"), is(false)); + } + + @Test + void shouldSupportAllVersionsExcludingProvided() { + VersionSupportChecker supportedVersions = create( + CheckSupportingVersionsExcluded.class.getAnnotation(AemVersion.class)); + assertThat(supportedVersions.supports("6.1"), is(false)); + assertThat(supportedVersions.supports("2.1"), is(false)); + assertThat(supportedVersions.supports("4.8"), is(false)); + assertThat(supportedVersions.supports("6.0"), is(true)); + assertThat(supportedVersions.supports("2.2"), is(true)); + } + + @Test + void shouldUseDefaultVersionWhenProvidedVersionIsEmptyOrNull() { + VersionSupportChecker supportedVersions = create( + CheckSupportingDefaultVersion.class.getAnnotation(AemVersion.class)); + assertThat(supportedVersions.supports(DEFAULT_AEM_VERSION), is(true)); + assertThat(supportedVersions.supports(""), is(true)); + assertThat(supportedVersions.supports(null), is(true)); + } + + @Test + void shouldThrowExceptionWhenVersionToSupportIsIncorrect() { + VersionSupportChecker supportedVersions = create( + CheckSupportingVersionsExcluded.class.getAnnotation(AemVersion.class)); + assertThrows(IllegalArgumentException.class, () -> supportedVersions.supports("f.1")); + } + + @Test + void shouldThrowExceptionWhenVersionIncorrectProvided1() { + assertThrows(IllegalArgumentException.class, () -> create(CheckWithIncorrectVersion1.class.getAnnotation(AemVersion.class))); + } + + @Test + void shouldThrowExceptionWhenVersionIncorrectProvided2() { + assertThrows(IllegalArgumentException.class, () -> create(CheckWithIncorrectVersion2.class.getAnnotation(AemVersion.class))); + } + + + @AemVersion( + all = true + ) + private class CheckSupportingAllVersions { + + } + + @AemVersion( + from = "5.1", + to = "6.4" + ) + private class CheckSupportingVersionsFromTo { + + } + + @AemVersion( + from = "10.1" + ) + private class CheckSupportingVersionsFrom { + + } + + @AemVersion( + to = "10.1" + ) + private class CheckSupportingVersionsTo { + + } + + @AemVersion( + included = {"6.1", "2.1", "4.8"} + ) + private class CheckSupportingVersionsIncluded { + + } + + @AemVersion( + all = true, + excluded = {"6.1", "2.1", "4.8"} + ) + private class CheckSupportingVersionsExcluded { + + } + + @AemVersion( + from = "5.6.7" + ) + private class CheckWithIncorrectVersion1 { + + } + + @AemVersion( + included = "a.b" + ) + private class CheckWithIncorrectVersion2 { + + } + + @AemVersion( + included = {DEFAULT_AEM_VERSION} + ) + private class CheckSupportingDefaultVersion { + + } + +} diff --git a/src/test/resources/rules/AEM-TEST.md b/src/test/resources/rules/AEM-TEST.md deleted file mode 100644 index 4a55210b..00000000 --- a/src/test/resources/rules/AEM-TEST.md +++ /dev/null @@ -1 +0,0 @@ -Test description. \ No newline at end of file diff --git a/src/test/resources/rules/com.cognifide.aemrules.extensions.RulesLoaderTest.RuleWithOnlyNameAttribute.md b/src/test/resources/rules/com.cognifide.aemrules.extensions.RulesLoaderTest.RuleWithOnlyNameAttribute.md deleted file mode 100644 index e69de29b..00000000 diff --git a/src/test/resources/scanner/testFile.html b/src/test/resources/scanner/testFile.html index ec8f57c8..aca99c8a 100644 --- a/src/test/resources/scanner/testFile.html +++ b/src/test/resources/scanner/testFile.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/resources/sensor/comment.html b/src/test/resources/sensor/comment.html index d7b5feef..3ab34150 100644 --- a/src/test/resources/sensor/comment.html +++ b/src/test/resources/sensor/comment.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/resources/sensor/error.html b/src/test/resources/sensor/error.html index 8973e548..29d61280 100644 --- a/src/test/resources/sensor/error.html +++ b/src/test/resources/sensor/error.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/resources/sensor/nestedTags.html b/src/test/resources/sensor/nestedTags.html index b0a435cd..4e3f33d0 100644 --- a/src/test/resources/sensor/nestedTags.html +++ b/src/test/resources/sensor/nestedTags.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/test/resources/sensor/test.html b/src/test/resources/sensor/test.html index ef26da5c..b99e99d5 100644 --- a/src/test/resources/sensor/test.html +++ b/src/test/resources/sensor/test.html @@ -3,7 +3,7 @@ #%L AEM Rules for SonarQube %% - Copyright (C) 2015-2019 Wunderman Thompson Technology + Copyright (C) 2015-2024 VML %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.