├── src ├── main │ └── java │ │ └── com │ │ └── mickaelb │ │ ├── api │ │ ├── StatementType.java │ │ ├── AssertHibernateL2CCount.java │ │ ├── AssertHibernateSQLCount.java │ │ └── QueryAssertions.java │ │ └── integration │ │ ├── spring │ │ ├── assertions │ │ │ ├── HibernateStatementAssertionValidator.java │ │ │ ├── HibernateAssertCountException.java │ │ │ ├── l2c │ │ │ │ ├── HibernateL2CAssertionResult.java │ │ │ │ └── HibernateL2CAssertionResults.java │ │ │ └── sql │ │ │ │ ├── HibernateStatementAssertionResults.java │ │ │ │ └── HibernateStatementAssertionResult.java │ │ ├── AssertTestListener.java │ │ ├── HibernateAssertTestListener.java │ │ ├── HibernateL2CCountTestListener.java │ │ └── HibernateSQLCountTestListener.java │ │ └── hibernate │ │ ├── HibernateStatementParser.java │ │ ├── HibernateStatementListener.java │ │ ├── HibernateStatementInspector.java │ │ ├── JSQLHibernateStatementParser.java │ │ └── HibernateStatementStatistics.java └── test │ └── java │ └── com │ └── mickaelb │ ├── integration │ ├── hibernate │ │ ├── HibernateStatementInspectorTest.java │ │ ├── JSQLHibernateStatementParserTest.java │ │ └── HibernateStatementStatisticsTest.java │ └── spring │ │ ├── assertions │ │ ├── l2c │ │ │ ├── HibernateL2CAssertionResultsTest.java │ │ │ └── HibernateL2CAssertionResultTest.java │ │ └── sql │ │ │ ├── HibernateStatementAssertionResultsTest.java │ │ │ └── HibernateStatementAssertionResultTest.java │ │ ├── HibernateAssertTestListenerTest.java │ │ ├── HibernateL2CCountTestListenerTest.java │ │ └── HibernateSQLCountTestListenerTest.java │ └── api │ └── QueryAssertionsTest.java ├── .gitignore ├── .github └── workflows │ └── build.yaml ├── .mvn └── wrapper │ └── maven-wrapper.properties ├── README.md ├── pom.xml ├── mvnw.cmd ├── mvnw └── LICENSE /src/main/java/com/mickaelb/api/StatementType.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.api; 2 | 3 | public enum StatementType { 4 | SELECT, INSERT, UPDATE, DELETE 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/spring/assertions/HibernateStatementAssertionValidator.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring.assertions; 2 | 3 | public interface HibernateStatementAssertionValidator { 4 | void validate(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/hibernate/HibernateStatementParser.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.hibernate; 2 | 3 | public interface HibernateStatementParser { 4 | 5 | void parseSqlStatement(String sql, HibernateStatementListener statementCountListener); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/spring/assertions/HibernateAssertCountException.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring.assertions; 2 | 3 | public class HibernateAssertCountException extends RuntimeException { 4 | 5 | public HibernateAssertCountException(String message) { 6 | super(message); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/hibernate/HibernateStatementListener.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.hibernate; 2 | 3 | public interface HibernateStatementListener { 4 | 5 | void notifySelectStatement(String sql); 6 | void notifyUpdateStatement(String sql); 7 | void notifyInsertStatement(String sql); 8 | void notifyDeleteStatement(String sql); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/spring/AssertTestListener.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring; 2 | 3 | import org.springframework.test.context.TestContext; 4 | 5 | public interface AssertTestListener { 6 | 7 | void beforeTestClass(TestContext testContext); 8 | void beforeTestMethod(TestContext testContext); 9 | void afterTestMethod(TestContext testContext); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/api/AssertHibernateL2CCount.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.api; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target(ElementType.METHOD) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface AssertHibernateL2CCount { 11 | 12 | int hits() default 0; 13 | 14 | int misses() default 0; 15 | 16 | int puts() default 0; 17 | } 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/api/AssertHibernateSQLCount.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.api; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target(ElementType.METHOD) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface AssertHibernateSQLCount { 11 | 12 | int selects() default 0; 13 | 14 | int inserts() default 0; 15 | 16 | int updates() default 0; 17 | 18 | int deletes() default 0; 19 | } 20 | -------------------------------------------------------------------------------- /.github/workflows/build.yaml: -------------------------------------------------------------------------------- 1 | name: Build Project 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - name: Checkout code 17 | uses: actions/checkout@v3 18 | 19 | - name: Import GPG Key 20 | uses: crazy-max/ghaction-import-gpg@v1 21 | env: 22 | GPG_PRIVATE_KEY: ${{ secrets.GPG_SIGNING_KEY }} 23 | PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} 24 | 25 | - name: Set up JDK 26 | uses: actions/setup-java@v3 27 | with: 28 | distribution: 'temurin' 29 | java-version: '17' 30 | cache: maven 31 | 32 | - name: Build 33 | run: chmod +x mvnw && ./mvnw clean install 34 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/hibernate/HibernateStatementInspector.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.hibernate; 2 | 3 | import org.hibernate.resource.jdbc.spi.StatementInspector; 4 | 5 | /** 6 | * NOT Thread-Safe since it is meant to be used by Spring tests that are not multi-threaded 7 | * ThreadLocal does not work because a test can span on multiple threads (ex: a test executing a HTTP request on the server) 8 | */ 9 | public class HibernateStatementInspector implements StatementInspector { 10 | 11 | private static final HibernateStatementStatistics statistics = new HibernateStatementStatistics(); 12 | 13 | private HibernateStatementParser statementParser = new JSQLHibernateStatementParser(); 14 | 15 | @Override 16 | public String inspect(String sql) { 17 | statementParser.parseSqlStatement(sql, statistics); 18 | return sql; 19 | } 20 | 21 | public static HibernateStatementStatistics getStatistics() { 22 | return statistics; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | wrapperVersion=3.3.2 18 | distributionType=only-script 19 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.6/apache-maven-3.9.6-bin.zip 20 | -------------------------------------------------------------------------------- /src/test/java/com/mickaelb/integration/hibernate/HibernateStatementInspectorTest.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.hibernate; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.junit.jupiter.api.extension.ExtendWith; 5 | import org.mockito.InjectMocks; 6 | import org.mockito.Mock; 7 | import org.mockito.junit.jupiter.MockitoExtension; 8 | 9 | import static org.junit.jupiter.api.Assertions.*; 10 | import static org.mockito.Mockito.*; 11 | 12 | @ExtendWith(MockitoExtension.class) 13 | class HibernateStatementInspectorTest { 14 | 15 | @InjectMocks 16 | HibernateStatementInspector model; 17 | 18 | @Mock 19 | HibernateStatementParser statementParser; 20 | 21 | @Test 22 | public void _inspect() { 23 | String actual = model.inspect("SELECT * FROM Post"); 24 | 25 | assertEquals("SELECT * FROM Post", actual, "output is the same as the input"); 26 | verify(statementParser, description("parser is called")).parseSqlStatement("SELECT * FROM Post", HibernateStatementInspector.getStatistics()); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/spring/assertions/l2c/HibernateL2CAssertionResult.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring.assertions.l2c; 2 | 3 | import com.mickaelb.integration.spring.assertions.HibernateAssertCountException; 4 | import com.mickaelb.integration.spring.assertions.HibernateStatementAssertionValidator; 5 | 6 | public class HibernateL2CAssertionResult implements HibernateStatementAssertionValidator { 7 | 8 | public enum CacheAction {HIT, MISS, PUT} 9 | 10 | private CacheAction type; 11 | private long actual; 12 | private long expected; 13 | 14 | public HibernateL2CAssertionResult(CacheAction type, long actual, long expected) { 15 | this.type = type; 16 | this.actual = actual; 17 | this.expected = expected; 18 | } 19 | 20 | public boolean isInError() { 21 | return actual != expected; 22 | } 23 | 24 | public String getErrorMessage() { 25 | return "Expected " + expected + " L2C cache " + type.name() + " but got " + actual; 26 | } 27 | 28 | @Override 29 | public void validate() { 30 | if (this.isInError()) { 31 | throw new HibernateAssertCountException(this.getErrorMessage()); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/hibernate/JSQLHibernateStatementParser.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.hibernate; 2 | 3 | import net.sf.jsqlparser.JSQLParserException; 4 | import net.sf.jsqlparser.parser.CCJSqlParserUtil; 5 | import net.sf.jsqlparser.statement.Statement; 6 | import net.sf.jsqlparser.statement.delete.Delete; 7 | import net.sf.jsqlparser.statement.insert.Insert; 8 | import net.sf.jsqlparser.statement.select.Select; 9 | import net.sf.jsqlparser.statement.update.Update; 10 | 11 | public class JSQLHibernateStatementParser implements HibernateStatementParser { 12 | 13 | @Override 14 | public void parseSqlStatement(String sql, HibernateStatementListener statementCountListener) { 15 | try { 16 | Statement statement = CCJSqlParserUtil.parse(sql); 17 | 18 | if (statement instanceof Delete) { 19 | statementCountListener.notifyDeleteStatement(sql); 20 | } else if (statement instanceof Insert) { 21 | statementCountListener.notifyInsertStatement(sql); 22 | } else if (statement instanceof Select) { 23 | statementCountListener.notifySelectStatement(sql); 24 | } else if (statement instanceof Update) { 25 | statementCountListener.notifyUpdateStatement(sql); 26 | } 27 | } catch (JSQLParserException ignored) { 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/spring/assertions/l2c/HibernateL2CAssertionResults.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring.assertions.l2c; 2 | 3 | import com.mickaelb.integration.spring.assertions.HibernateAssertCountException; 4 | import com.mickaelb.integration.spring.assertions.HibernateStatementAssertionValidator; 5 | 6 | import java.util.List; 7 | import java.util.stream.Collectors; 8 | 9 | public class HibernateL2CAssertionResults implements HibernateStatementAssertionValidator { 10 | 11 | private final List assertionResults; 12 | 13 | public HibernateL2CAssertionResults(List assertionResults) { 14 | this.assertionResults = assertionResults; 15 | } 16 | 17 | @Override 18 | public void validate() { 19 | List assertionsInError = assertionResults.stream() 20 | .filter(HibernateL2CAssertionResult::isInError) 21 | .collect(Collectors.toList()); 22 | 23 | if (assertionsInError.size() > 0) { 24 | String errorMessages = System.lineSeparator() + assertionsInError.stream() 25 | .map(HibernateL2CAssertionResult::getErrorMessage) 26 | .collect(Collectors.joining(System.lineSeparator())); 27 | throw new HibernateAssertCountException(errorMessages); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/spring/assertions/sql/HibernateStatementAssertionResults.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring.assertions.sql; 2 | 3 | import com.mickaelb.integration.spring.assertions.HibernateStatementAssertionValidator; 4 | import com.mickaelb.integration.spring.assertions.HibernateAssertCountException; 5 | 6 | import java.util.List; 7 | import java.util.stream.Collectors; 8 | 9 | public class HibernateStatementAssertionResults implements HibernateStatementAssertionValidator { 10 | 11 | private final List assertionResults; 12 | 13 | public HibernateStatementAssertionResults(List assertionResults) { 14 | this.assertionResults = assertionResults; 15 | } 16 | 17 | @Override 18 | public void validate() { 19 | List assertionsInError = assertionResults.stream() 20 | .filter(HibernateStatementAssertionResult::isInError) 21 | .collect(Collectors.toList()); 22 | 23 | if (!assertionsInError.isEmpty()) { 24 | String errorMessages = System.lineSeparator() + assertionsInError.stream() 25 | .map(HibernateStatementAssertionResult::getErrorMessage) 26 | .collect(Collectors.joining(System.lineSeparator() + System.lineSeparator())); 27 | throw new HibernateAssertCountException(errorMessages); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/mickaelb/integration/spring/assertions/l2c/HibernateL2CAssertionResultsTest.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring.assertions.l2c; 2 | 3 | import com.mickaelb.integration.spring.assertions.HibernateAssertCountException; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import java.util.List; 7 | 8 | import static com.mickaelb.integration.spring.assertions.l2c.HibernateL2CAssertionResult.CacheAction.*; 9 | import static org.junit.jupiter.api.Assertions.*; 10 | 11 | class HibernateL2CAssertionResultsTest { 12 | 13 | @Test 14 | public void _results_empty() { 15 | HibernateL2CAssertionResults model = new HibernateL2CAssertionResults(List.of()); 16 | 17 | assertDoesNotThrow(model::validate, "an empty list does not throw an error"); 18 | } 19 | 20 | @Test 21 | public void _results_invalid() { 22 | HibernateL2CAssertionResults model = new HibernateL2CAssertionResults(List.of( 23 | new HibernateL2CAssertionResult(HIT, 1, 2), 24 | new HibernateL2CAssertionResult(MISS, 2, 1), 25 | new HibernateL2CAssertionResult(PUT, 1, 1) 26 | )); 27 | 28 | HibernateAssertCountException actual = assertThrows(HibernateAssertCountException.class, model::validate, "validation error is thrown"); 29 | 30 | String expected = System.lineSeparator() + 31 | "Expected 2 L2C cache HIT but got 1" + System.lineSeparator() + 32 | "Expected 1 L2C cache MISS but got 2"; 33 | 34 | assertEquals(expected, actual.getMessage(), "the error message is correct"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/spring/assertions/sql/HibernateStatementAssertionResult.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring.assertions.sql; 2 | 3 | import com.mickaelb.api.StatementType; 4 | import com.mickaelb.integration.spring.assertions.HibernateAssertCountException; 5 | import com.mickaelb.integration.spring.assertions.HibernateStatementAssertionValidator; 6 | 7 | import java.util.List; 8 | import java.util.stream.Collectors; 9 | 10 | public class HibernateStatementAssertionResult implements HibernateStatementAssertionValidator { 11 | 12 | private StatementType type; 13 | private List statements; 14 | private int expected; 15 | 16 | public HibernateStatementAssertionResult(StatementType type, List statements, int expected) { 17 | this.type = type; 18 | this.statements = statements; 19 | this.expected = expected; 20 | } 21 | 22 | public boolean isInError() { 23 | return statements.size() != expected; 24 | } 25 | 26 | public String getErrorMessage() { 27 | String header = "Expected " + expected + " " + type.name() + " but got " + statements.size() + ":" + System.lineSeparator(); 28 | String statementsDetail = statements.stream() 29 | .map(statement -> " => '" + statement + "'") 30 | .collect(Collectors.joining(System.lineSeparator())); 31 | return header + statementsDetail; 32 | } 33 | 34 | @Override 35 | public void validate() { 36 | if (this.isInError()) { 37 | throw new HibernateAssertCountException(this.getErrorMessage()); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/spring/HibernateAssertTestListener.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring; 2 | 3 | 4 | import org.springframework.core.Ordered; 5 | import org.springframework.test.context.TestContext; 6 | import org.springframework.test.context.TestExecutionListener; 7 | 8 | import java.util.List; 9 | import java.util.Objects; 10 | 11 | public class HibernateAssertTestListener implements TestExecutionListener, Ordered { 12 | 13 | private List testListeners = List.of(new HibernateSQLCountTestListener(), new HibernateL2CCountTestListener()); 14 | 15 | @Override 16 | public void beforeTestClass(TestContext testContext) { 17 | testListeners.forEach(assertTestListener -> assertTestListener.beforeTestClass(testContext)); 18 | } 19 | 20 | @Override 21 | public void beforeTestMethod(TestContext testContext) { 22 | testListeners.forEach(assertTestListener -> assertTestListener.beforeTestMethod(testContext)); 23 | } 24 | 25 | @Override 26 | public void afterTestMethod(TestContext testContext) { 27 | testListeners.forEach(assertTestListener -> assertTestListener.afterTestMethod(testContext)); 28 | } 29 | 30 | /** 31 | * Low precedence for executing before {@link org.springframework.test.context.transaction.TransactionalTestExecutionListener} 32 | * closes the transaction and to have the ability to flush the EntityManager 33 | */ 34 | @Override 35 | public int getOrder() { 36 | return Ordered.LOWEST_PRECEDENCE; 37 | } 38 | 39 | public void setTestListeners(List testListeners) { 40 | Objects.requireNonNull(testListeners); 41 | this.testListeners = testListeners; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/com/mickaelb/integration/spring/assertions/l2c/HibernateL2CAssertionResultTest.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring.assertions.l2c; 2 | 3 | import com.mickaelb.integration.spring.assertions.HibernateAssertCountException; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import static com.mickaelb.integration.spring.assertions.l2c.HibernateL2CAssertionResult.CacheAction.HIT; 7 | import static org.junit.jupiter.api.Assertions.*; 8 | 9 | class HibernateL2CAssertionResultTest { 10 | 11 | @Test 12 | public void _isInError_true() { 13 | HibernateL2CAssertionResult model = new HibernateL2CAssertionResult(HIT, 2, 1); 14 | 15 | assertTrue(model.isInError(), "the result is in error"); 16 | } 17 | 18 | @Test 19 | public void _isInError_false() { 20 | HibernateL2CAssertionResult model = new HibernateL2CAssertionResult(HIT, 1, 1); 21 | 22 | assertFalse(model.isInError(), "the result is not in error"); 23 | } 24 | 25 | @Test 26 | public void _validate_does_not_throw() { 27 | HibernateL2CAssertionResult model = new HibernateL2CAssertionResult(HIT, 1, 1); 28 | 29 | assertDoesNotThrow(model::validate); 30 | } 31 | 32 | @Test 33 | public void _validate_throws() { 34 | HibernateL2CAssertionResult model = new HibernateL2CAssertionResult(HIT, 2, 1); 35 | 36 | assertThrows(HibernateAssertCountException.class, model::validate); 37 | } 38 | 39 | @Test 40 | public void _getErrorMessage() { 41 | HibernateL2CAssertionResult model = new HibernateL2CAssertionResult(HIT, 2, 1); 42 | 43 | String expected = "Expected 1 L2C cache HIT but got 2"; 44 | assertEquals(expected, model.getErrorMessage(), "the error message is correct"); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/hibernate/HibernateStatementStatistics.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.hibernate; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class HibernateStatementStatistics implements HibernateStatementListener { 7 | 8 | private final List selectStatements = new ArrayList<>(); 9 | private final List updateStatements = new ArrayList<>(); 10 | private final List insertStatements = new ArrayList<>(); 11 | private final List deleteStatements = new ArrayList<>(); 12 | 13 | public void resetStatistics() { 14 | selectStatements.clear(); 15 | updateStatements.clear(); 16 | insertStatements.clear(); 17 | deleteStatements.clear(); 18 | } 19 | 20 | @Override 21 | public void notifySelectStatement(String sql) { 22 | selectStatements.add(sql); 23 | } 24 | 25 | @Override 26 | public void notifyUpdateStatement(String sql) { 27 | updateStatements.add(sql); 28 | } 29 | 30 | @Override 31 | public void notifyInsertStatement(String sql) { 32 | insertStatements.add(sql); 33 | } 34 | 35 | @Override 36 | public void notifyDeleteStatement(String sql) { 37 | deleteStatements.add(sql); 38 | } 39 | 40 | public List getSelectStatements() { 41 | return new ArrayList<>(selectStatements); 42 | } 43 | 44 | public List getUpdateStatements() { 45 | return new ArrayList<>(updateStatements); 46 | } 47 | 48 | public List getInsertStatements() { 49 | return new ArrayList<>(insertStatements); 50 | } 51 | 52 | public List getDeleteStatements() { 53 | return new ArrayList<>(deleteStatements) ; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/test/java/com/mickaelb/integration/spring/HibernateAssertTestListenerTest.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring; 2 | 3 | import com.mickaelb.api.AssertHibernateL2CCount; 4 | import com.mickaelb.api.AssertHibernateSQLCount; 5 | import com.mickaelb.integration.hibernate.HibernateStatementStatistics; 6 | import jakarta.persistence.EntityManager; 7 | import org.hibernate.SessionFactory; 8 | import org.junit.jupiter.api.BeforeEach; 9 | import org.junit.jupiter.api.Test; 10 | import org.junit.jupiter.api.extension.ExtendWith; 11 | import org.mockito.Answers; 12 | import org.mockito.InjectMocks; 13 | import org.mockito.Mock; 14 | import org.mockito.junit.jupiter.MockitoExtension; 15 | import org.springframework.test.context.TestContext; 16 | 17 | import java.util.List; 18 | import java.util.function.Supplier; 19 | 20 | import static org.mockito.Mockito.*; 21 | 22 | @ExtendWith(MockitoExtension.class) 23 | class HibernateAssertTestListenerTest { 24 | 25 | @InjectMocks 26 | HibernateAssertTestListener model; 27 | 28 | @Mock 29 | TestContext testContext; 30 | 31 | @Mock 32 | AssertTestListener assertTestListener; 33 | 34 | @BeforeEach 35 | public void init() { 36 | model.setTestListeners(List.of(assertTestListener)); 37 | } 38 | 39 | @Test 40 | public void _beforeTestClass() { 41 | model.beforeTestClass(testContext); 42 | 43 | verify(assertTestListener, description("child method must be called")).beforeTestClass(testContext); 44 | } 45 | 46 | @Test 47 | public void _beforeTestMethod() { 48 | model.beforeTestMethod(testContext); 49 | 50 | verify(assertTestListener, description("child method must be called")).beforeTestMethod(testContext); 51 | } 52 | 53 | @Test 54 | public void _afterTestMethod() { 55 | model.afterTestMethod(testContext); 56 | 57 | verify(assertTestListener, description("child method must be called")).afterTestMethod(testContext); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/test/java/com/mickaelb/integration/spring/assertions/sql/HibernateStatementAssertionResultsTest.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring.assertions.sql; 2 | 3 | import com.mickaelb.integration.spring.assertions.HibernateAssertCountException; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import java.util.List; 7 | 8 | import static com.mickaelb.api.StatementType.*; 9 | import static org.junit.jupiter.api.Assertions.*; 10 | 11 | class HibernateStatementAssertionResultsTest { 12 | 13 | static final String EOL = System.lineSeparator(); 14 | 15 | @Test 16 | public void _results_empty() { 17 | HibernateStatementAssertionResults model = new HibernateStatementAssertionResults(List.of()); 18 | 19 | assertDoesNotThrow(model::validate, "an empty list does not throw an error"); 20 | } 21 | 22 | @Test 23 | public void _results_invalid() { 24 | HibernateStatementAssertionResults model = new HibernateStatementAssertionResults(List.of( 25 | new HibernateStatementAssertionResult(SELECT, List.of("SELECT 1"), 2), 26 | new HibernateStatementAssertionResult(INSERT, List.of("INSERT 1","INSERT 2"), 1), 27 | new HibernateStatementAssertionResult(DELETE, List.of("DELETE 1"), 1), 28 | new HibernateStatementAssertionResult(UPDATE, List.of("UPDATE 1"), 2) 29 | )); 30 | 31 | HibernateAssertCountException actual = assertThrows(HibernateAssertCountException.class, model::validate, "validation error is thrown"); 32 | 33 | String expected = EOL + 34 | "Expected 2 SELECT but got 1:" + EOL + 35 | " => 'SELECT 1'" + EOL + 36 | EOL + 37 | "Expected 1 INSERT but got 2:" + EOL + 38 | " => 'INSERT 1'" + EOL + 39 | " => 'INSERT 2'" + EOL + 40 | EOL + 41 | "Expected 2 UPDATE but got 1:" + EOL + 42 | " => 'UPDATE 1'"; 43 | assertEquals(expected, actual.getMessage(), "the error message is correct"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/com/mickaelb/integration/spring/assertions/sql/HibernateStatementAssertionResultTest.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring.assertions.sql; 2 | 3 | import com.mickaelb.integration.spring.assertions.HibernateAssertCountException; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import java.util.List; 7 | 8 | import static com.mickaelb.api.StatementType.SELECT; 9 | import static org.junit.jupiter.api.Assertions.*; 10 | 11 | class HibernateStatementAssertionResultTest { 12 | 13 | @Test 14 | public void _isInError_true() { 15 | HibernateStatementAssertionResult model = new HibernateStatementAssertionResult(SELECT, List.of("SELECT 1", "SELECT 2"), 1); 16 | 17 | assertTrue(model.isInError(), "the result is in error"); 18 | } 19 | 20 | @Test 21 | public void _isInError_false() { 22 | HibernateStatementAssertionResult model = new HibernateStatementAssertionResult(SELECT, List.of("SELECT 1"), 1); 23 | 24 | assertFalse(model.isInError(), "the result is not in error"); 25 | } 26 | 27 | @Test 28 | public void _validate_does_not_throw() { 29 | HibernateStatementAssertionResult model = new HibernateStatementAssertionResult(SELECT, List.of("SELECT 1"), 1); 30 | 31 | assertDoesNotThrow(model::validate); 32 | } 33 | 34 | @Test 35 | public void _validate_throws() { 36 | HibernateStatementAssertionResult model = new HibernateStatementAssertionResult(SELECT, List.of("SELECT 1", "SELECT 2"), 1); 37 | 38 | assertThrows(HibernateAssertCountException.class, model::validate); 39 | } 40 | 41 | @Test 42 | public void _getErrorMessage() { 43 | HibernateStatementAssertionResult model = new HibernateStatementAssertionResult(SELECT, List.of("SELECT 1", "SELECT 2"), 1); 44 | 45 | String expected = "Expected 1 SELECT but got 2:" + System.lineSeparator() + 46 | " => 'SELECT 1'" + System.lineSeparator() + 47 | " => 'SELECT 2'"; 48 | assertEquals(expected, model.getErrorMessage(), "the error message is correct"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/test/java/com/mickaelb/integration/hibernate/JSQLHibernateStatementParserTest.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.hibernate; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.junit.jupiter.api.extension.ExtendWith; 5 | import org.mockito.InjectMocks; 6 | import org.mockito.Mock; 7 | import org.mockito.junit.jupiter.MockitoExtension; 8 | 9 | import static org.mockito.Mockito.*; 10 | 11 | @ExtendWith(MockitoExtension.class) 12 | class JSQLHibernateStatementParserTest { 13 | 14 | @InjectMocks 15 | JSQLHibernateStatementParser model; 16 | 17 | @Mock 18 | HibernateStatementListener hibernateStatementListener; 19 | 20 | @Test 21 | public void _parseSqlStatement_select() { 22 | model.parseSqlStatement("SELECT * FROM Post", hibernateStatementListener); 23 | 24 | verify(hibernateStatementListener, description("the correct notifier is called")).notifySelectStatement("SELECT * FROM Post"); 25 | } 26 | 27 | @Test 28 | public void _parseSqlStatement_update() { 29 | model.parseSqlStatement("UPDATE Post p SET p.title = ?", hibernateStatementListener); 30 | 31 | verify(hibernateStatementListener, description("the correct notifier is called")).notifyUpdateStatement("UPDATE Post p SET p.title = ?"); 32 | } 33 | 34 | @Test 35 | public void _parseSqlStatement_insert() { 36 | model.parseSqlStatement("INSERT INTO Post VALUES (?)", hibernateStatementListener); 37 | 38 | verify(hibernateStatementListener, description("the correct notifier is called")).notifyInsertStatement("INSERT INTO Post VALUES (?)"); 39 | } 40 | 41 | @Test 42 | public void _parseSqlStatement_delete() { 43 | model.parseSqlStatement("DELETE FROM Post", hibernateStatementListener); 44 | 45 | verify(hibernateStatementListener, description("the correct notifier is called")).notifyDeleteStatement("DELETE FROM Post"); 46 | } 47 | 48 | @Test 49 | public void _incorrect_statement_should_not_throw() { 50 | model.parseSqlStatement("This is not really SQL", hibernateStatementListener); 51 | 52 | verifyNoInteractions(hibernateStatementListener); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/com/mickaelb/integration/hibernate/HibernateStatementStatisticsTest.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.hibernate; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.junit.jupiter.api.extension.ExtendWith; 5 | import org.mockito.InjectMocks; 6 | import org.mockito.junit.jupiter.MockitoExtension; 7 | 8 | import static org.junit.jupiter.api.Assertions.*; 9 | 10 | @ExtendWith(MockitoExtension.class) 11 | class HibernateStatementStatisticsTest { 12 | 13 | @InjectMocks 14 | HibernateStatementStatistics model; 15 | 16 | @Test 17 | public void _default_state() { 18 | assertEquals(0, model.getSelectStatements().size(), "the count is initialized to 0"); 19 | assertEquals(0, model.getInsertStatements().size(), "the count is initialized to 0"); 20 | assertEquals(0, model.getUpdateStatements().size(), "the count is initialized to 0"); 21 | assertEquals(0, model.getDeleteStatements().size(), "the count is initialized to 0"); 22 | } 23 | 24 | @Test 25 | public void _reset() { 26 | model.notifySelectStatement("SELECT * FROM Post"); 27 | model.notifyInsertStatement("INSERT INTO Post VALUES (X)"); 28 | model.notifyUpdateStatement("UPDATE Post SET X=X"); 29 | model.notifyDeleteStatement("DELETE * FROM Post"); 30 | 31 | model.resetStatistics(); 32 | 33 | assertEquals(0, model.getSelectStatements().size(), "the count is reset to 0"); 34 | assertEquals(0, model.getInsertStatements().size(), "the count is reset to 0"); 35 | assertEquals(0, model.getUpdateStatements().size(), "the count is reset to 0"); 36 | assertEquals(0, model.getDeleteStatements().size(), "the count is reset to 0"); 37 | } 38 | 39 | @Test 40 | public void _notify_increments() { 41 | model.notifySelectStatement("SELECT * FROM Post"); 42 | model.notifyInsertStatement("INSERT INTO Post VALUES (X)"); 43 | model.notifyUpdateStatement("UPDATE Post SET X=X"); 44 | model.notifyDeleteStatement("DELETE * FROM Post"); 45 | 46 | assertEquals(1, model.getSelectStatements().size(), "the count is incremented"); 47 | assertEquals(1, model.getInsertStatements().size(), "the count is incremented"); 48 | assertEquals(1, model.getUpdateStatements().size(), "the count is incremented"); 49 | assertEquals(1, model.getDeleteStatements().size(), "the count is incremented"); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/spring/HibernateL2CCountTestListener.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring; 2 | 3 | import com.mickaelb.api.AssertHibernateL2CCount; 4 | import com.mickaelb.integration.spring.assertions.l2c.HibernateL2CAssertionResult; 5 | import com.mickaelb.integration.spring.assertions.l2c.HibernateL2CAssertionResults; 6 | import org.hibernate.SessionFactory; 7 | import org.hibernate.stat.Statistics; 8 | import org.springframework.test.context.TestContext; 9 | 10 | import java.util.List; 11 | 12 | import static com.mickaelb.integration.spring.assertions.l2c.HibernateL2CAssertionResult.CacheAction.*; 13 | 14 | public class HibernateL2CCountTestListener implements AssertTestListener { 15 | 16 | private Statistics sessionFactoryStatistics; 17 | 18 | @Override 19 | public void beforeTestClass(TestContext testContext) { 20 | SessionFactory sessionFactory = testContext.getApplicationContext() 21 | .getAutowireCapableBeanFactory() 22 | .getBean(SessionFactory.class); 23 | 24 | sessionFactoryStatistics = sessionFactory.getStatistics(); 25 | sessionFactoryStatistics.setStatisticsEnabled(true); 26 | } 27 | 28 | @Override 29 | public void beforeTestMethod(TestContext testContext) { 30 | sessionFactoryStatistics.clear(); 31 | } 32 | 33 | @Override 34 | public void afterTestMethod(TestContext testContext) { 35 | AssertHibernateL2CCount l2cCountAnnotation = testContext.getTestMethod().getAnnotation(AssertHibernateL2CCount.class); 36 | if (l2cCountAnnotation != null) { 37 | evaluateL2CCount(l2cCountAnnotation); 38 | } 39 | } 40 | 41 | private void evaluateL2CCount(AssertHibernateL2CCount annotation) { 42 | HibernateL2CAssertionResults assertionResults = new HibernateL2CAssertionResults(List.of( 43 | new HibernateL2CAssertionResult(HIT, sessionFactoryStatistics.getSecondLevelCacheHitCount(), annotation.hits()), 44 | new HibernateL2CAssertionResult(MISS, sessionFactoryStatistics.getSecondLevelCacheMissCount(), annotation.misses()), 45 | new HibernateL2CAssertionResult(PUT, sessionFactoryStatistics.getSecondLevelCachePutCount(), annotation.puts()) 46 | )); 47 | assertionResults.validate(); 48 | } 49 | 50 | Statistics getSessionFactoryStatistics() { 51 | return sessionFactoryStatistics; 52 | } 53 | 54 | void setSessionFactoryStatistics(Statistics sessionFactoryStatistics) { 55 | this.sessionFactoryStatistics = sessionFactoryStatistics; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/integration/spring/HibernateSQLCountTestListener.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring; 2 | 3 | import com.mickaelb.api.AssertHibernateSQLCount; 4 | import com.mickaelb.integration.hibernate.HibernateStatementInspector; 5 | import com.mickaelb.integration.spring.assertions.sql.HibernateStatementAssertionResult; 6 | import com.mickaelb.integration.spring.assertions.sql.HibernateStatementAssertionResults; 7 | import com.mickaelb.integration.hibernate.HibernateStatementStatistics; 8 | import jakarta.persistence.EntityManager; 9 | import org.springframework.test.context.TestContext; 10 | import org.springframework.test.context.transaction.TestTransaction; 11 | 12 | import java.util.List; 13 | import java.util.function.Supplier; 14 | 15 | import static com.mickaelb.api.StatementType.*; 16 | 17 | public class HibernateSQLCountTestListener implements AssertTestListener{ 18 | 19 | private Supplier statisticsSupplier = HibernateStatementInspector::getStatistics; 20 | private Supplier transactionAvailabilitySupplier = TestTransaction::isActive; 21 | 22 | @Override 23 | public void beforeTestClass(TestContext testContext) { 24 | } 25 | 26 | @Override 27 | public void beforeTestMethod(TestContext testContext) { 28 | statisticsSupplier.get().resetStatistics(); 29 | } 30 | 31 | @Override 32 | public void afterTestMethod(TestContext testContext) { 33 | AssertHibernateSQLCount sqlCountAnnotation = testContext.getTestMethod().getAnnotation(AssertHibernateSQLCount.class); 34 | if (sqlCountAnnotation != null) { 35 | flushExistingPersistenceContext(testContext, transactionAvailabilitySupplier); 36 | evaluateSQLStatementCount(sqlCountAnnotation); 37 | } 38 | } 39 | 40 | private void flushExistingPersistenceContext(TestContext testContext, Supplier transactionAvailabilitySupplier) { 41 | if (transactionAvailabilitySupplier.get()) { 42 | EntityManager entityManager = testContext.getApplicationContext() 43 | .getAutowireCapableBeanFactory() 44 | .getBean(EntityManager.class); 45 | entityManager.flush(); 46 | } 47 | } 48 | 49 | private void evaluateSQLStatementCount(AssertHibernateSQLCount annotation) { 50 | HibernateStatementAssertionResults assertionResults = new HibernateStatementAssertionResults(List.of( 51 | new HibernateStatementAssertionResult(SELECT, statisticsSupplier.get().getSelectStatements(), annotation.selects()), 52 | new HibernateStatementAssertionResult(UPDATE, statisticsSupplier.get().getUpdateStatements(), annotation.updates()), 53 | new HibernateStatementAssertionResult(INSERT, statisticsSupplier.get().getInsertStatements(), annotation.inserts()), 54 | new HibernateStatementAssertionResult(DELETE, statisticsSupplier.get().getDeleteStatements(), annotation.deletes()) 55 | )); 56 | assertionResults.validate(); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/mickaelb/api/QueryAssertions.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.api; 2 | 3 | import com.mickaelb.integration.spring.assertions.sql.HibernateStatementAssertionResult; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | import java.util.function.Supplier; 8 | import java.util.stream.Collectors; 9 | 10 | import static com.mickaelb.api.StatementType.*; 11 | import static com.mickaelb.integration.hibernate.HibernateStatementInspector.getStatistics; 12 | 13 | public class QueryAssertions { 14 | 15 | private static final Map>> STATEMENT_SUPPLIERS = Map.of( 16 | INSERT, () -> getStatistics().getInsertStatements(), 17 | UPDATE, () -> getStatistics().getUpdateStatements(), 18 | SELECT, () -> getStatistics().getSelectStatements(), 19 | DELETE, () -> getStatistics().getDeleteStatements() 20 | ); 21 | 22 | private QueryAssertions() { 23 | } 24 | 25 | public static void assertInsertCount(int expectedInsertCount, Runnable runnable) { 26 | doAssertStatementCount(runnable, INSERT, expectedInsertCount); 27 | } 28 | 29 | public static void assertUpdateCount(int expectedUpdateCount, Runnable runnable) { 30 | doAssertStatementCount(runnable, UPDATE, expectedUpdateCount); 31 | } 32 | 33 | public static void assertSelectCount(int expectedSelectCount, Runnable runnable) { 34 | doAssertStatementCount(runnable, SELECT, expectedSelectCount); 35 | } 36 | 37 | public static void assertDeleteCount(int expectedDeleteCount, Runnable runnable) { 38 | doAssertStatementCount(runnable, DELETE, expectedDeleteCount); 39 | } 40 | 41 | public static void assertStatementCount(Map expectedCounts, Runnable runnable) { 42 | Map sizesBeforeExecution = expectedCounts.keySet().stream() 43 | .collect(Collectors.toMap( 44 | statementType -> statementType, 45 | statementType -> STATEMENT_SUPPLIERS.get(statementType).get().size() 46 | )); 47 | 48 | runnable.run(); 49 | 50 | for (Map.Entry entry : expectedCounts.entrySet()) { 51 | StatementType statementType = entry.getKey(); 52 | int expectedCount = entry.getValue(); 53 | 54 | Supplier> statementSupplier = STATEMENT_SUPPLIERS.get(statementType); 55 | List fullStatements = statementSupplier.get(); 56 | 57 | int sizeBeforeExecution = sizesBeforeExecution.get(statementType); 58 | List executionScopedStatements = fullStatements.subList(sizeBeforeExecution, fullStatements.size()); 59 | 60 | HibernateStatementAssertionResult assertionResult = new HibernateStatementAssertionResult(statementType, executionScopedStatements, expectedCount); 61 | assertionResult.validate(); 62 | } 63 | } 64 | 65 | private static void doAssertStatementCount(Runnable runnable, StatementType statementType, int expectedCount) { 66 | Supplier> statementSupplier = STATEMENT_SUPPLIERS.get(statementType); 67 | int sizeBeforeExecution = statementSupplier.get().size(); 68 | runnable.run(); 69 | 70 | List fullStatements = statementSupplier.get(); 71 | List executionScopedStatements = fullStatements.subList(sizeBeforeExecution, fullStatements.size()); 72 | 73 | HibernateStatementAssertionResult assertionResult = new HibernateStatementAssertionResult(statementType, executionScopedStatements, expectedCount); 74 | assertionResult.validate(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/test/java/com/mickaelb/integration/spring/HibernateL2CCountTestListenerTest.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring; 2 | 3 | import com.mickaelb.api.AssertHibernateL2CCount; 4 | import org.hibernate.SessionFactory; 5 | import org.hibernate.stat.Statistics; 6 | import org.junit.jupiter.api.Test; 7 | import org.junit.jupiter.api.extension.ExtendWith; 8 | import org.mockito.Answers; 9 | import org.mockito.InjectMocks; 10 | import org.mockito.Mock; 11 | import org.mockito.junit.jupiter.MockitoExtension; 12 | import org.springframework.test.context.TestContext; 13 | 14 | import static org.junit.jupiter.api.Assertions.assertSame; 15 | import static org.mockito.Mockito.*; 16 | 17 | @ExtendWith(MockitoExtension.class) 18 | class HibernateL2CCountTestListenerTest { 19 | public static class FakeClass { 20 | @AssertHibernateL2CCount 21 | public void annotatedMethod() { 22 | 23 | } 24 | 25 | public void notAnnotatedMethod() { 26 | 27 | } 28 | } 29 | 30 | @InjectMocks 31 | HibernateL2CCountTestListener model; 32 | 33 | @Mock 34 | Statistics statistics; 35 | 36 | @Mock(answer = Answers.RETURNS_DEEP_STUBS) 37 | TestContext testContext; 38 | 39 | @Test 40 | public void _beforeTestClass() { 41 | SessionFactory sessionFactory = mock(SessionFactory.class); 42 | when(sessionFactory.getStatistics()).thenReturn(statistics); 43 | when(testContext.getApplicationContext().getAutowireCapableBeanFactory().getBean(SessionFactory.class)).thenReturn(sessionFactory); 44 | model.setSessionFactoryStatistics(null); 45 | 46 | model.beforeTestClass(testContext); 47 | 48 | assertSame(statistics, model.getSessionFactoryStatistics(), "the statistics object is set"); 49 | verify(statistics, description("statistics is explicitly enabled during initialization")).setStatisticsEnabled(true); 50 | 51 | } 52 | 53 | @Test 54 | public void _beforeTestMethod_no_annotation() { 55 | model.beforeTestMethod(testContext); 56 | 57 | verify(statistics, description("the statistics are cleared")).clear(); 58 | } 59 | 60 | @Test 61 | public void _beforeTestMethod_with_annotation() { 62 | model.beforeTestMethod(testContext); 63 | 64 | verify(statistics, description("the statistics are cleared")).clear(); 65 | } 66 | 67 | @Test 68 | public void _afterTestMethod_without_annotation() throws NoSuchMethodException { 69 | when(testContext.getTestMethod()).thenReturn(HibernateL2CCountTestListenerTest.FakeClass.class.getMethod("notAnnotatedMethod")); 70 | 71 | model.afterTestMethod(testContext); 72 | 73 | verify(statistics, times(0).description("The statistics count is not fetched")).getSecondLevelCacheHitCount(); 74 | verify(statistics, times(0).description("The statistics count is not fetched")).getSecondLevelCacheMissCount(); 75 | verify(statistics, times(0).description("The statistics count is not fetched")).getSecondLevelCachePutCount(); 76 | } 77 | 78 | @Test 79 | public void _afterTestMethod_with_annotation_with_transaction() throws NoSuchMethodException { 80 | when(testContext.getTestMethod()).thenReturn(HibernateL2CCountTestListenerTest.FakeClass.class.getMethod("annotatedMethod")); 81 | 82 | model.afterTestMethod(testContext); 83 | 84 | verify(statistics, description("The statistics count is fetched")).getSecondLevelCacheHitCount(); 85 | verify(statistics, description("The statistics count is fetched")).getSecondLevelCacheMissCount(); 86 | verify(statistics, description("The statistics count is fetched")).getSecondLevelCachePutCount(); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/test/java/com/mickaelb/integration/spring/HibernateSQLCountTestListenerTest.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.integration.spring; 2 | 3 | import com.mickaelb.api.AssertHibernateSQLCount; 4 | import com.mickaelb.integration.hibernate.HibernateStatementStatistics; 5 | import jakarta.persistence.EntityManager; 6 | import org.junit.jupiter.api.Test; 7 | import org.junit.jupiter.api.extension.ExtendWith; 8 | import org.mockito.Answers; 9 | import org.mockito.InjectMocks; 10 | import org.mockito.Mock; 11 | import org.mockito.junit.jupiter.MockitoExtension; 12 | import org.springframework.test.context.TestContext; 13 | 14 | import java.util.function.Supplier; 15 | 16 | import static org.mockito.Mockito.*; 17 | import static org.mockito.Mockito.description; 18 | 19 | @ExtendWith(MockitoExtension.class) 20 | class HibernateSQLCountTestListenerTest { 21 | 22 | public static class FakeClass { 23 | @AssertHibernateSQLCount 24 | public void annotatedMethod() { 25 | 26 | } 27 | 28 | public void notAnnotatedMethod() { 29 | 30 | } 31 | } 32 | 33 | @InjectMocks 34 | HibernateSQLCountTestListener model; 35 | 36 | @Mock 37 | Supplier statisticsSupplier; 38 | 39 | @Mock 40 | Supplier transactionAvailabilitySupplier; 41 | 42 | @Mock(answer = Answers.RETURNS_DEEP_STUBS) 43 | TestContext testContext; 44 | 45 | @Test 46 | public void _beforeTestMethod_no_annotation() { 47 | when(statisticsSupplier.get()).thenReturn(mock(HibernateStatementStatistics.class)); 48 | 49 | model.beforeTestMethod(testContext); 50 | 51 | verify(statisticsSupplier.get(), description("the reset method is called")).resetStatistics(); 52 | } 53 | 54 | @Test 55 | public void _beforeTestMethod_with_annotation() { 56 | when(statisticsSupplier.get()).thenReturn(mock(HibernateStatementStatistics.class)); 57 | 58 | model.beforeTestMethod(testContext); 59 | 60 | verify(statisticsSupplier.get(), description("the reset method is called")).resetStatistics(); 61 | } 62 | 63 | @Test 64 | public void _afterTestMethod_without_annotation() throws NoSuchMethodException { 65 | when(testContext.getTestMethod()).thenReturn(HibernateSQLCountTestListenerTest.FakeClass.class.getMethod("notAnnotatedMethod")); 66 | 67 | model.afterTestMethod(testContext); 68 | 69 | verify(testContext, times(0).description("EntityManager is NOT flushed")).getApplicationContext(); 70 | } 71 | 72 | @Test 73 | public void _afterTestMethod_with_annotation_without_transaction() throws NoSuchMethodException { 74 | when(testContext.getTestMethod()).thenReturn(HibernateSQLCountTestListenerTest.FakeClass.class.getMethod("annotatedMethod")); 75 | when(transactionAvailabilitySupplier.get()).thenReturn(false); 76 | when(statisticsSupplier.get()).thenReturn(mock(HibernateStatementStatistics.class)); 77 | 78 | model.afterTestMethod(testContext); 79 | 80 | verify(testContext, times(0).description("EntityManager is NOT flushed")).getApplicationContext(); 81 | verify(statisticsSupplier.get(), description("statements are fetched")).getSelectStatements(); 82 | verify(statisticsSupplier.get(), description("statements are fetched")).getUpdateStatements(); 83 | verify(statisticsSupplier.get(), description("statements are fetched")).getInsertStatements(); 84 | verify(statisticsSupplier.get(), description("statements are fetched")).getDeleteStatements(); 85 | } 86 | 87 | @Test 88 | public void _afterTestMethod_with_annotation_with_transaction() throws NoSuchMethodException { 89 | EntityManager entityManager = mock(EntityManager.class); 90 | when(testContext.getTestMethod()).thenReturn(HibernateSQLCountTestListenerTest.FakeClass.class.getMethod("annotatedMethod")); 91 | when(testContext.getApplicationContext().getAutowireCapableBeanFactory().getBean(EntityManager.class)).thenReturn(entityManager); 92 | when(statisticsSupplier.get()).thenReturn(mock(HibernateStatementStatistics.class)); 93 | when(transactionAvailabilitySupplier.get()).thenReturn(true); 94 | 95 | model.afterTestMethod(testContext); 96 | 97 | verify(entityManager, description("EntityManager is flushed")).flush(); 98 | verify(statisticsSupplier.get(), description("statements are fetched")).getSelectStatements(); 99 | verify(statisticsSupplier.get(), description("statements are fetched")).getUpdateStatements(); 100 | verify(statisticsSupplier.get(), description("statements are fetched")).getInsertStatements(); 101 | verify(statisticsSupplier.get(), description("statements are fetched")).getDeleteStatements(); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hibernate SQL Query Assertions for Spring 2 | 3 | Hibernate is a powerful ORM, but you need to have control over the executed SQL queries to avoid **huge performance problems** (N+1 selects, batch insert not working...) 4 | 5 | You can enable SQL query logging, this is a great help in dev, but not in production. This tool helps you to count the **executed SQL queries by Hibernate in your integration tests, it can assert L2C statistics too**. 6 | 7 | It consists of just a Hibernate SQL inspector service and a Spring Test Listener that controls it (no proxy around the Datasource). 8 | 9 | The assertion will work seamlessly whether you're testing Spring repositories or doing HTTP integration tests. 10 | 11 | ## Examples 12 | 13 | A full-working demo of the examples below [is available here](https://github.com/Lemick/demo-hibernate-query-utils) 14 | 15 | *Tested versions*: Hibernate 5 & 6 16 | 17 | ### Assert SQL statements declaratively 18 | 19 | You just have to add the `@AssertHibernateSQLCount` annotation to your test and it will verify the SQL statements (SELECT, UPDATE, INSERT, DELETE) count at the end of the test : 20 | 21 | ```java 22 | @Test 23 | @Transactional 24 | @AssertHibernateSQLCount(inserts = 6) 25 | void create_two_blog_posts() { 26 | BlogPost post_1 = new BlogPost("Blog post 1"); 27 | post_1.addComment(new PostComment("Good article")); 28 | post_1.addComment(new PostComment("Very interesting")); 29 | blogPostRepository.save(post_1); 30 | 31 | BlogPost post_2 = new BlogPost("Blog post 2"); 32 | post_2.addComment(new PostComment("Nice")); 33 | post_2.addComment(new PostComment("So cool, thanks")); 34 | blogPostRepository.save(post_2); 35 | } 36 | ``` 37 | If the actual count is different, an exception is thrown with the executed statements: 38 | ``` 39 | com.mickaelb.assertions.HibernateAssertCountException: 40 | Expected 5 INSERT but got 6: 41 | => '/* insert com.lemick.demo.entity.BlogPost */ insert into blog_post (id, title) values (default, ?)' 42 | => '/* insert com.lemick.demo.entity.PostComment */ insert into post_comment (id, blog_post_id, content) values (default, ?, ?)' 43 | => '/* insert com.lemick.demo.entity.PostComment */ insert into post_comment (id, blog_post_id, content) values (default, ?, ?)' 44 | => '/* insert com.lemick.demo.entity.BlogPost */ insert into blog_post (id, title) values (default, ?)' 45 | => '/* insert com.lemick.demo.entity.PostComment */ insert into post_comment (id, blog_post_id, content) values (default, ?, ?)' 46 | => '/* insert com.lemick.demo.entity.PostComment */ insert into post_comment (id, blog_post_id, content) values (default, ?, ?)' 47 | ``` 48 | 49 | ### Assert SQL statements programmatically 50 | 51 | You can also assert statements from several transactions in your test using the programmatic API: 52 | ```java 53 | @Test 54 | void multiple_assertions_using_programmatic_api() { 55 | QueryAssertions.assertInsertCount(2, () -> { 56 | BlogPost post_1 = new BlogPost("Blog post 1"); 57 | post_1.addComment(new PostComment("Good article")); 58 | blogPostRepository.save(post_1); 59 | }); 60 | 61 | QueryAssertions.assertSelectCount(1, () -> blogPostRepository.findById(1L)); 62 | 63 | // Or even multiple asserts at once 64 | QueryAssertions.assertStatementCount(Map.of(INSERT, 2, SELECT, 1), () -> { 65 | BlogPost post_1 = new BlogPost("Blog post 1"); 66 | post_1.addComment(new PostComment("Good article")); 67 | blogPostRepository.save(post_1); 68 | 69 | blogPostRepository.findById(1L); 70 | }); 71 | } 72 | ``` 73 | 74 | ### Assert L2C statistics declaratively 75 | 76 | It supports assertions on Hibernate level two cache statistics, useful for checking that your entities are cached correctly and that they will stay forever: 77 | ```java 78 | @Test 79 | @AssertHibernateL2CCount(misses = 1, puts = 1, hits = 1) 80 | void create_one_post_and_read_it() { 81 | doInTransaction(() -> { 82 | BlogPost post_1 = new BlogPost("Blog post 1"); 83 | blogPostRepository.save(post_1); 84 | }); 85 | 86 | doInTransaction(() -> { 87 | blogPostRepository.findById(1L); // 1 MISS + 1 PUT 88 | }); 89 | 90 | doInTransaction(() -> { 91 | blogPostRepository.findById(1L); // 1 HIT 92 | }); 93 | } 94 | ``` 95 | ## How to integrate 96 | 1. Import the dependency 97 | ```xml 98 | 99 | com.mickaelb 100 | hibernate-query-asserts 101 | 2.2.0 102 | 103 | ``` 104 | 2. Register the integration with Hibernate, you just need to add this key in your configuration (here for yml): 105 | 106 | spring: 107 | jpa: 108 | properties: 109 | hibernate.session_factory.statement_inspector: com.mickaelb.integration.hibernate.HibernateStatementInspector 110 | 111 | 3. Register the Spring TestListener that will launch the SQL inspection if the annotation is present: 112 | 113 | * By adding the listener on each of your integration test: 114 | ```java 115 | @SpringBootTest 116 | @TestExecutionListeners( 117 | listeners = HibernateAssertTestListener.class, 118 | mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS 119 | ) 120 | class MySpringIntegrationTest { 121 | ... 122 | } 123 | ``` 124 | 125 | * **OR** by adding a **META-INF/spring.factories** file that contains the definition, that will register the listener for all your tests: 126 | ``` 127 | org.springframework.test.context.TestExecutionListener=com.mickaelb.integration.spring.HibernateAssertTestListener 128 | ``` 129 | -------------------------------------------------------------------------------- /src/test/java/com/mickaelb/api/QueryAssertionsTest.java: -------------------------------------------------------------------------------- 1 | package com.mickaelb.api; 2 | 3 | import com.mickaelb.integration.hibernate.HibernateStatementInspector; 4 | import com.mickaelb.integration.spring.assertions.HibernateAssertCountException; 5 | import org.junit.jupiter.api.BeforeEach; 6 | import org.junit.jupiter.api.Test; 7 | 8 | import java.util.Map; 9 | 10 | import static com.mickaelb.api.StatementType.*; 11 | import static org.junit.jupiter.api.Assertions.assertThrows; 12 | 13 | public class QueryAssertionsTest { 14 | 15 | @BeforeEach 16 | public void setUp() { 17 | HibernateStatementInspector.getStatistics().resetStatistics(); 18 | } 19 | 20 | @Test 21 | public void _assert_insert_count_success() { 22 | QueryAssertions.assertInsertCount(2, () -> { 23 | HibernateStatementInspector.getStatistics().notifyInsertStatement("INSERT INTO table test (id) VALUES (uuid())"); 24 | HibernateStatementInspector.getStatistics().notifyInsertStatement("INSERT INTO table test (id) VALUES (uuid())"); 25 | }); 26 | 27 | QueryAssertions.assertInsertCount(1, () -> HibernateStatementInspector.getStatistics().notifyInsertStatement("INSERT INTO table test (id) VALUES (uuid())")); 28 | } 29 | 30 | @Test 31 | public void _assert_insert_count_failure() { 32 | Runnable insertRunnable = () -> { 33 | HibernateStatementInspector.getStatistics().notifyInsertStatement("INSERT INTO table test (id) VALUES (uuid())"); 34 | HibernateStatementInspector.getStatistics().notifyInsertStatement("INSERT INTO table test (id) VALUES (uuid())"); 35 | }; 36 | 37 | assertThrows(HibernateAssertCountException.class, () -> QueryAssertions.assertInsertCount(3, insertRunnable)); 38 | } 39 | 40 | @Test 41 | public void _assert_update_count_success() { 42 | QueryAssertions.assertUpdateCount(2, () -> { 43 | HibernateStatementInspector.getStatistics().notifyUpdateStatement("UPDATE table SET id=1"); 44 | HibernateStatementInspector.getStatistics().notifyUpdateStatement("UPDATE table SET id=1"); 45 | }); 46 | 47 | QueryAssertions.assertUpdateCount(1, () -> { 48 | HibernateStatementInspector.getStatistics().notifyUpdateStatement("UPDATE table SET id=1"); 49 | }); 50 | } 51 | 52 | @Test 53 | public void _assert_update_count_failure() { 54 | Runnable updateRunnable = () -> { 55 | HibernateStatementInspector.getStatistics().notifyUpdateStatement("UPDATE table SET id=1"); 56 | }; 57 | 58 | assertThrows(HibernateAssertCountException.class, () -> QueryAssertions.assertUpdateCount(2, updateRunnable)); 59 | } 60 | 61 | @Test 62 | public void _assert_select_count_success() { 63 | QueryAssertions.assertSelectCount(2, () -> { 64 | HibernateStatementInspector.getStatistics().notifySelectStatement("SELECT * FROM table"); 65 | HibernateStatementInspector.getStatistics().notifySelectStatement("SELECT * FROM table"); 66 | }); 67 | 68 | QueryAssertions.assertSelectCount(1, () -> { 69 | HibernateStatementInspector.getStatistics().notifySelectStatement("SELECT * FROM table"); 70 | }); 71 | } 72 | 73 | @Test 74 | public void _assert_select_count_failure() { 75 | Runnable selectRunnable = () -> { 76 | HibernateStatementInspector.getStatistics().notifySelectStatement("SELECT * FROM table"); 77 | HibernateStatementInspector.getStatistics().notifySelectStatement("SELECT * FROM table"); 78 | }; 79 | 80 | assertThrows(HibernateAssertCountException.class, () -> QueryAssertions.assertSelectCount(4, selectRunnable)); 81 | } 82 | 83 | @Test 84 | public void _assert_delete_count_success() { 85 | QueryAssertions.assertDeleteCount(2, () -> { 86 | HibernateStatementInspector.getStatistics().notifyDeleteStatement("DELETE FROM table WHERE 1=1"); 87 | HibernateStatementInspector.getStatistics().notifyDeleteStatement("DELETE FROM table WHERE 1=1"); 88 | }); 89 | 90 | QueryAssertions.assertDeleteCount(1, () -> { 91 | HibernateStatementInspector.getStatistics().notifyDeleteStatement("DELETE FROM table WHERE 1=1"); 92 | }); 93 | } 94 | 95 | @Test 96 | public void _assert_delete_count_failure() { 97 | Runnable deleteRunnable = () -> { 98 | HibernateStatementInspector.getStatistics().notifyDeleteStatement("DELETE FROM table WHERE 1=1"); 99 | }; 100 | 101 | assertThrows(HibernateAssertCountException.class, () -> QueryAssertions.assertDeleteCount(2, deleteRunnable)); 102 | } 103 | 104 | @Test 105 | public void _assert_multiple_count_success() { 106 | QueryAssertions.assertStatementCount(Map.of(DELETE, 2, UPDATE, 1, SELECT, 0), () -> { 107 | HibernateStatementInspector.getStatistics().notifyDeleteStatement("DELETE FROM table WHERE 1=1"); 108 | HibernateStatementInspector.getStatistics().notifyDeleteStatement("DELETE FROM table WHERE 1=1"); 109 | HibernateStatementInspector.getStatistics().notifyUpdateStatement("UPDATE table SET id=1"); 110 | }); 111 | 112 | QueryAssertions.assertStatementCount(Map.of(DELETE, 2, SELECT, 1, INSERT, 0), () -> { 113 | HibernateStatementInspector.getStatistics().notifyDeleteStatement("DELETE FROM table WHERE 1=1"); 114 | HibernateStatementInspector.getStatistics().notifyDeleteStatement("DELETE FROM table WHERE 1=1"); 115 | HibernateStatementInspector.getStatistics().notifySelectStatement("SELECT * FROM table"); 116 | }); 117 | } 118 | 119 | @Test 120 | public void _assert_multiple_count_failure() { 121 | assertThrows(HibernateAssertCountException.class, () -> { 122 | QueryAssertions.assertStatementCount(Map.of(DELETE, 2, UPDATE, 1, SELECT, 0), () -> { 123 | HibernateStatementInspector.getStatistics().notifyDeleteStatement("DELETE FROM table WHERE 1=1"); 124 | HibernateStatementInspector.getStatistics().notifyDeleteStatement("DELETE FROM table WHERE 1=1"); 125 | }); 126 | }); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mickaelb 8 | hibernate-query-asserts 9 | 2.2.0-SNAPSHOT 10 | 11 | ${project.groupId}:${project.artifactId} 12 | A library that can assert statement generated by Hibernate in Spring tests 13 | https://github.com/Lemick/hibernate-query-asserts 14 | 15 | 16 | 17 | The Apache License, Version 2.0 18 | https://www.apache.org/licenses/LICENSE-2.0.txt 19 | 20 | 21 | 22 | 23 | 24 | Mickaël Beguin 25 | sidfloyd84@gmail.com 26 | https://mickaelb.com 27 | 28 | 29 | 30 | 31 | scm:git:git://github.com/lemick/hibernate-query-asserts.git 32 | scm:git:ssh://github.com:lemick/hibernate-query-asserts.git 33 | https://github.com/lemick/hibernate-query-asserts/tree/master 34 | 35 | 36 | 37 | 38 | ossrh 39 | https://s01.oss.sonatype.org/content/repositories/snapshots 40 | 41 | 42 | ossrh 43 | https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/ 44 | 45 | 46 | 47 | 48 | 11 49 | 11 50 | 2.6.6 51 | 5.6.7.Final 52 | 5.1 53 | 5.8.2 54 | 4.4.0 55 | 56 | 57 | 58 | 59 | com.github.jsqlparser 60 | jsqlparser 61 | ${jsqlparser.version} 62 | 63 | 64 | org.hibernate 65 | hibernate-core-jakarta 66 | ${hibernate-core-jakarta.version} 67 | provided 68 | 69 | 70 | org.springframework.boot 71 | spring-boot-starter-test 72 | ${spring-boot-starter-test.version} 73 | provided 74 | 75 | 76 | org.junit.jupiter 77 | junit-jupiter-engine 78 | ${junit-jupiter-engine.version} 79 | test 80 | 81 | 82 | org.mockito 83 | mockito-junit-jupiter 84 | ${mockito-junit-jupiter.version} 85 | test 86 | 87 | 88 | 89 | 90 | 91 | 92 | org.apache.maven.plugins 93 | maven-source-plugin 94 | 3.2.1 95 | 96 | 97 | attach-sources 98 | 99 | jar-no-fork 100 | 101 | 102 | 103 | 104 | 105 | org.apache.maven.plugins 106 | maven-javadoc-plugin 107 | 3.3.2 108 | 109 | 110 | attach-javadocs 111 | 112 | jar 113 | 114 | 115 | 116 | 117 | 118 | org.apache.maven.plugins 119 | maven-surefire-plugin 120 | 3.0.0-M6 121 | 122 | 123 | org.apache.maven.plugins 124 | maven-gpg-plugin 125 | 3.0.1 126 | 127 | 128 | sign-artifacts 129 | verify 130 | 131 | sign 132 | 133 | 134 | 135 | 136 | 137 | org.sonatype.plugins 138 | nexus-staging-maven-plugin 139 | 1.7.0 140 | true 141 | 142 | ossrh 143 | https://s01.oss.sonatype.org/ 144 | true 145 | 146 | 147 | 148 | 149 | 150 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | <# : batch portion 2 | @REM ---------------------------------------------------------------------------- 3 | @REM Licensed to the Apache Software Foundation (ASF) under one 4 | @REM or more contributor license agreements. See the NOTICE file 5 | @REM distributed with this work for additional information 6 | @REM regarding copyright ownership. The ASF licenses this file 7 | @REM to you under the Apache License, Version 2.0 (the 8 | @REM "License"); you may not use this file except in compliance 9 | @REM with the License. You may obtain a copy of the License at 10 | @REM 11 | @REM http://www.apache.org/licenses/LICENSE-2.0 12 | @REM 13 | @REM Unless required by applicable law or agreed to in writing, 14 | @REM software distributed under the License is distributed on an 15 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | @REM KIND, either express or implied. See the License for the 17 | @REM specific language governing permissions and limitations 18 | @REM under the License. 19 | @REM ---------------------------------------------------------------------------- 20 | 21 | @REM ---------------------------------------------------------------------------- 22 | @REM Apache Maven Wrapper startup batch script, version 3.3.2 23 | @REM 24 | @REM Optional ENV vars 25 | @REM MVNW_REPOURL - repo url base for downloading maven distribution 26 | @REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven 27 | @REM MVNW_VERBOSE - true: enable verbose log; others: silence the output 28 | @REM ---------------------------------------------------------------------------- 29 | 30 | @IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) 31 | @SET __MVNW_CMD__= 32 | @SET __MVNW_ERROR__= 33 | @SET __MVNW_PSMODULEP_SAVE=%PSModulePath% 34 | @SET PSModulePath= 35 | @FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( 36 | IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) 37 | ) 38 | @SET PSModulePath=%__MVNW_PSMODULEP_SAVE% 39 | @SET __MVNW_PSMODULEP_SAVE= 40 | @SET __MVNW_ARG0_NAME__= 41 | @SET MVNW_USERNAME= 42 | @SET MVNW_PASSWORD= 43 | @IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) 44 | @echo Cannot start maven from wrapper >&2 && exit /b 1 45 | @GOTO :EOF 46 | : end batch / begin powershell #> 47 | 48 | $ErrorActionPreference = "Stop" 49 | if ($env:MVNW_VERBOSE -eq "true") { 50 | $VerbosePreference = "Continue" 51 | } 52 | 53 | # calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties 54 | $distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl 55 | if (!$distributionUrl) { 56 | Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" 57 | } 58 | 59 | switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { 60 | "maven-mvnd-*" { 61 | $USE_MVND = $true 62 | $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" 63 | $MVN_CMD = "mvnd.cmd" 64 | break 65 | } 66 | default { 67 | $USE_MVND = $false 68 | $MVN_CMD = $script -replace '^mvnw','mvn' 69 | break 70 | } 71 | } 72 | 73 | # apply MVNW_REPOURL and calculate MAVEN_HOME 74 | # maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ 75 | if ($env:MVNW_REPOURL) { 76 | $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } 77 | $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" 78 | } 79 | $distributionUrlName = $distributionUrl -replace '^.*/','' 80 | $distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' 81 | $MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" 82 | if ($env:MAVEN_USER_HOME) { 83 | $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" 84 | } 85 | $MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' 86 | $MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" 87 | 88 | if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { 89 | Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" 90 | Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" 91 | exit $? 92 | } 93 | 94 | if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { 95 | Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" 96 | } 97 | 98 | # prepare tmp dir 99 | $TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile 100 | $TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" 101 | $TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null 102 | trap { 103 | if ($TMP_DOWNLOAD_DIR.Exists) { 104 | try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } 105 | catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } 106 | } 107 | } 108 | 109 | New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null 110 | 111 | # Download and Install Apache Maven 112 | Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." 113 | Write-Verbose "Downloading from: $distributionUrl" 114 | Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" 115 | 116 | $webclient = New-Object System.Net.WebClient 117 | if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { 118 | $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) 119 | } 120 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 121 | $webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null 122 | 123 | # If specified, validate the SHA-256 sum of the Maven distribution zip file 124 | $distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum 125 | if ($distributionSha256Sum) { 126 | if ($USE_MVND) { 127 | Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." 128 | } 129 | Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash 130 | if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { 131 | Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." 132 | } 133 | } 134 | 135 | # unzip and move 136 | Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null 137 | Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null 138 | try { 139 | Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null 140 | } catch { 141 | if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { 142 | Write-Error "fail to move MAVEN_HOME" 143 | } 144 | } finally { 145 | try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } 146 | catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } 147 | } 148 | 149 | Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" 150 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Apache Maven Wrapper startup batch script, version 3.3.2 23 | # 24 | # Optional ENV vars 25 | # ----------------- 26 | # JAVA_HOME - location of a JDK home dir, required when download maven via java source 27 | # MVNW_REPOURL - repo url base for downloading maven distribution 28 | # MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven 29 | # MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output 30 | # ---------------------------------------------------------------------------- 31 | 32 | set -euf 33 | [ "${MVNW_VERBOSE-}" != debug ] || set -x 34 | 35 | # OS specific support. 36 | native_path() { printf %s\\n "$1"; } 37 | case "$(uname)" in 38 | CYGWIN* | MINGW*) 39 | [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" 40 | native_path() { cygpath --path --windows "$1"; } 41 | ;; 42 | esac 43 | 44 | # set JAVACMD and JAVACCMD 45 | set_java_home() { 46 | # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched 47 | if [ -n "${JAVA_HOME-}" ]; then 48 | if [ -x "$JAVA_HOME/jre/sh/java" ]; then 49 | # IBM's JDK on AIX uses strange locations for the executables 50 | JAVACMD="$JAVA_HOME/jre/sh/java" 51 | JAVACCMD="$JAVA_HOME/jre/sh/javac" 52 | else 53 | JAVACMD="$JAVA_HOME/bin/java" 54 | JAVACCMD="$JAVA_HOME/bin/javac" 55 | 56 | if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then 57 | echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 58 | echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 59 | return 1 60 | fi 61 | fi 62 | else 63 | JAVACMD="$( 64 | 'set' +e 65 | 'unset' -f command 2>/dev/null 66 | 'command' -v java 67 | )" || : 68 | JAVACCMD="$( 69 | 'set' +e 70 | 'unset' -f command 2>/dev/null 71 | 'command' -v javac 72 | )" || : 73 | 74 | if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then 75 | echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 76 | return 1 77 | fi 78 | fi 79 | } 80 | 81 | # hash string like Java String::hashCode 82 | hash_string() { 83 | str="${1:-}" h=0 84 | while [ -n "$str" ]; do 85 | char="${str%"${str#?}"}" 86 | h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) 87 | str="${str#?}" 88 | done 89 | printf %x\\n $h 90 | } 91 | 92 | verbose() { :; } 93 | [ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } 94 | 95 | die() { 96 | printf %s\\n "$1" >&2 97 | exit 1 98 | } 99 | 100 | trim() { 101 | # MWRAPPER-139: 102 | # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. 103 | # Needed for removing poorly interpreted newline sequences when running in more 104 | # exotic environments such as mingw bash on Windows. 105 | printf "%s" "${1}" | tr -d '[:space:]' 106 | } 107 | 108 | # parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties 109 | while IFS="=" read -r key value; do 110 | case "${key-}" in 111 | distributionUrl) distributionUrl=$(trim "${value-}") ;; 112 | distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; 113 | esac 114 | done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" 115 | [ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" 116 | 117 | case "${distributionUrl##*/}" in 118 | maven-mvnd-*bin.*) 119 | MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ 120 | case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in 121 | *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; 122 | :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; 123 | :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; 124 | :Linux*x86_64*) distributionPlatform=linux-amd64 ;; 125 | *) 126 | echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 127 | distributionPlatform=linux-amd64 128 | ;; 129 | esac 130 | distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" 131 | ;; 132 | maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; 133 | *) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; 134 | esac 135 | 136 | # apply MVNW_REPOURL and calculate MAVEN_HOME 137 | # maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ 138 | [ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" 139 | distributionUrlName="${distributionUrl##*/}" 140 | distributionUrlNameMain="${distributionUrlName%.*}" 141 | distributionUrlNameMain="${distributionUrlNameMain%-bin}" 142 | MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" 143 | MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" 144 | 145 | exec_maven() { 146 | unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : 147 | exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" 148 | } 149 | 150 | if [ -d "$MAVEN_HOME" ]; then 151 | verbose "found existing MAVEN_HOME at $MAVEN_HOME" 152 | exec_maven "$@" 153 | fi 154 | 155 | case "${distributionUrl-}" in 156 | *?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; 157 | *) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; 158 | esac 159 | 160 | # prepare tmp dir 161 | if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then 162 | clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } 163 | trap clean HUP INT TERM EXIT 164 | else 165 | die "cannot create temp dir" 166 | fi 167 | 168 | mkdir -p -- "${MAVEN_HOME%/*}" 169 | 170 | # Download and Install Apache Maven 171 | verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." 172 | verbose "Downloading from: $distributionUrl" 173 | verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" 174 | 175 | # select .zip or .tar.gz 176 | if ! command -v unzip >/dev/null; then 177 | distributionUrl="${distributionUrl%.zip}.tar.gz" 178 | distributionUrlName="${distributionUrl##*/}" 179 | fi 180 | 181 | # verbose opt 182 | __MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' 183 | [ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v 184 | 185 | # normalize http auth 186 | case "${MVNW_PASSWORD:+has-password}" in 187 | '') MVNW_USERNAME='' MVNW_PASSWORD='' ;; 188 | has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; 189 | esac 190 | 191 | if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then 192 | verbose "Found wget ... using wget" 193 | wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" 194 | elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then 195 | verbose "Found curl ... using curl" 196 | curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" 197 | elif set_java_home; then 198 | verbose "Falling back to use Java to download" 199 | javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" 200 | targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" 201 | cat >"$javaSource" <<-END 202 | public class Downloader extends java.net.Authenticator 203 | { 204 | protected java.net.PasswordAuthentication getPasswordAuthentication() 205 | { 206 | return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); 207 | } 208 | public static void main( String[] args ) throws Exception 209 | { 210 | setDefault( new Downloader() ); 211 | java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); 212 | } 213 | } 214 | END 215 | # For Cygwin/MinGW, switch paths to Windows format before running javac and java 216 | verbose " - Compiling Downloader.java ..." 217 | "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" 218 | verbose " - Running Downloader.java ..." 219 | "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" 220 | fi 221 | 222 | # If specified, validate the SHA-256 sum of the Maven distribution zip file 223 | if [ -n "${distributionSha256Sum-}" ]; then 224 | distributionSha256Result=false 225 | if [ "$MVN_CMD" = mvnd.sh ]; then 226 | echo "Checksum validation is not supported for maven-mvnd." >&2 227 | echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 228 | exit 1 229 | elif command -v sha256sum >/dev/null; then 230 | if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then 231 | distributionSha256Result=true 232 | fi 233 | elif command -v shasum >/dev/null; then 234 | if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then 235 | distributionSha256Result=true 236 | fi 237 | else 238 | echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 239 | echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 240 | exit 1 241 | fi 242 | if [ $distributionSha256Result = false ]; then 243 | echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 244 | echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 245 | exit 1 246 | fi 247 | fi 248 | 249 | # unzip and move 250 | if command -v unzip >/dev/null; then 251 | unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" 252 | else 253 | tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" 254 | fi 255 | printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" 256 | mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" 257 | 258 | clean || : 259 | exec_maven "$@" 260 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------